fpowerkit 0.3.3rc0__tar.gz → 0.3.4__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 (32) hide show
  1. fpowerkit-0.3.4/.gitignore +9 -0
  2. {fpowerkit-0.3.3rc0/fpowerkit.egg-info → fpowerkit-0.3.4}/PKG-INFO +70 -52
  3. {fpowerkit-0.3.3rc0 → fpowerkit-0.3.4}/README.md +13 -0
  4. fpowerkit-0.3.3rc0/PKG-INFO → fpowerkit-0.3.4/desc.md +18 -28
  5. fpowerkit-0.3.4/fpowerkit/__init__.py +16 -0
  6. {fpowerkit-0.3.3rc0 → fpowerkit-0.3.4}/fpowerkit/bus.py +6 -1
  7. {fpowerkit-0.3.3rc0 → fpowerkit-0.3.4}/fpowerkit/cases.py +3 -1
  8. {fpowerkit-0.3.3rc0 → fpowerkit-0.3.4}/fpowerkit/ess.py +7 -3
  9. {fpowerkit-0.3.3rc0 → fpowerkit-0.3.4}/fpowerkit/gen.py +9 -4
  10. {fpowerkit-0.3.3rc0 → fpowerkit-0.3.4}/fpowerkit/grid.py +10 -8
  11. {fpowerkit-0.3.3rc0 → fpowerkit-0.3.4}/fpowerkit/island.py +6 -3
  12. {fpowerkit-0.3.3rc0 → fpowerkit-0.3.4}/fpowerkit/line.py +11 -7
  13. {fpowerkit-0.3.3rc0 → fpowerkit-0.3.4}/fpowerkit/pvwind.py +4 -1
  14. {fpowerkit-0.3.3rc0 → fpowerkit-0.3.4}/fpowerkit/solbase.py +3 -1
  15. {fpowerkit-0.3.3rc0 → fpowerkit-0.3.4}/fpowerkit/solcmb.py +2 -2
  16. {fpowerkit-0.3.3rc0 → fpowerkit-0.3.4}/fpowerkit/solcvx.py +8 -5
  17. {fpowerkit-0.3.3rc0 → fpowerkit-0.3.4}/fpowerkit/soldist.py +7 -5
  18. {fpowerkit-0.3.3rc0 → fpowerkit-0.3.4}/fpowerkit/soldss.py +5 -1
  19. {fpowerkit-0.3.3rc0 → fpowerkit-0.3.4}/fpowerkit/solldf.py +7 -6
  20. {fpowerkit-0.3.3rc0 → fpowerkit-0.3.4}/fpowerkit/solnt.py +11 -3
  21. {fpowerkit-0.3.3rc0 → fpowerkit-0.3.4}/fpowerkit/utils.py +31 -8
  22. fpowerkit-0.3.4/main.py +90 -0
  23. fpowerkit-0.3.4/pyproject.toml +51 -0
  24. fpowerkit-0.3.4/test.py +32 -0
  25. fpowerkit-0.3.3rc0/fpowerkit/__init__.py +0 -8
  26. fpowerkit-0.3.3rc0/fpowerkit.egg-info/SOURCES.txt +0 -25
  27. fpowerkit-0.3.3rc0/fpowerkit.egg-info/dependency_links.txt +0 -1
  28. fpowerkit-0.3.3rc0/fpowerkit.egg-info/requires.txt +0 -2
  29. fpowerkit-0.3.3rc0/fpowerkit.egg-info/top_level.txt +0 -1
  30. fpowerkit-0.3.3rc0/setup.cfg +0 -4
  31. fpowerkit-0.3.3rc0/setup.py +0 -21
  32. {fpowerkit-0.3.3rc0 → fpowerkit-0.3.4}/LICENSE +0 -0
@@ -0,0 +1,9 @@
1
+ __pycache__
2
+ .idea
3
+ .vscode
4
+ token
5
+ build
6
+ dist
7
+ *.egg-info
8
+ .venv
9
+ test/*.out
@@ -1,52 +1,70 @@
1
- Metadata-Version: 2.4
2
- Name: fpowerkit
3
- Version: 0.3.3rc0
4
- Summary: A PDN solver with multiple solutions.
5
- Author: fmy_xfk
6
- Classifier: Programming Language :: Python :: 3
7
- Classifier: License :: OSI Approved :: MIT License
8
- Classifier: Operating System :: OS Independent
9
- Requires-Python: >=3.8
10
- Description-Content-Type: text/markdown
11
- License-File: LICENSE
12
- Requires-Dist: feasytools>=0.0.21
13
- Requires-Dist: numpy>=1.19.0
14
- Dynamic: author
15
- Dynamic: classifier
16
- Dynamic: description
17
- Dynamic: description-content-type
18
- Dynamic: license-file
19
- Dynamic: requires-dist
20
- Dynamic: requires-python
21
- Dynamic: summary
22
-
23
- # FPowerKit - A power distribution network calculation component
24
-
25
- This is a package designed for power distribution network solving.
26
-
27
- 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):
28
-
29
- ```
30
- @ARTICLE{10970754,
31
- author={Qian, Tao and Fang, Mingyu and Hu, Qinran and Shao, Chengcheng and Zheng, Junyi},
32
- journal={IEEE Transactions on Smart Grid},
33
- title={V2Sim: An Open-Source Microscopic V2G Simulation Platform in Urban Power and Transportation Network},
34
- year={2025},
35
- volume={16},
36
- number={4},
37
- pages={3167-3178},
38
- keywords={Vehicle-to-grid;Partial discharges;Microscopy;Batteries;Planning;Discharges (electric);Optimization;Vehicle dynamics;Transportation;Roads;EV charging load simulation;microscopic EV behavior;vehicle-to-grid;charging station fault sensing},
39
- doi={10.1109/TSG.2025.3560976}}
40
- ```
41
-
42
- There are 3 modes for this package to work:
43
-
44
- - Optimal power flow (OPF): Use cvxpy to solve the optimal power flow and determine the output of the generators.
45
-
46
- - Power flow calculation: Use OpenDSS/GridCal/Inner Newton-Raphson method to solve the power flow.
47
-
48
- - Hybrid: Use OPF to determine the initial value, and then use OpenDSS/GridCal/Inner Newton-Raphson to perform accurate calculation.
49
-
50
- Since this package is still under development, the API is unstable and may be changed anytime.
51
-
52
- Please visit https://gitee.com/fmy_xfk/fpowerkit to read the detailed introduction and the usage.
1
+ Metadata-Version: 2.4
2
+ Name: fpowerkit
3
+ Version: 0.3.4
4
+ Summary: A PDN solver with multiple solutions.
5
+ Author: fmy-xfk
6
+ License-Expression: MIT
7
+ License-File: LICENSE
8
+ Classifier: License :: OSI Approved :: MIT License
9
+ Classifier: Operating System :: OS Independent
10
+ Classifier: Programming Language :: Python :: 3
11
+ Requires-Python: >=3.8
12
+ Requires-Dist: feasytools>=0.0.21
13
+ Provides-Extra: distflow
14
+ Requires-Dist: cvxpy; extra == 'distflow'
15
+ Requires-Dist: ecos; extra == 'distflow'
16
+ Requires-Dist: numpy>=1.19.0; extra == 'distflow'
17
+ Provides-Extra: dss
18
+ Requires-Dist: numpy>=1.19.0; extra == 'dss'
19
+ Requires-Dist: py-dss-interface; extra == 'dss'
20
+ Provides-Extra: full
21
+ Requires-Dist: cvxpy; extra == 'full'
22
+ Requires-Dist: ecos; extra == 'full'
23
+ Requires-Dist: numpy>=1.19.0; extra == 'full'
24
+ Requires-Dist: py-dss-interface; extra == 'full'
25
+ Provides-Extra: newton
26
+ Requires-Dist: numpy>=1.19.0; extra == 'newton'
27
+ Description-Content-Type: text/markdown
28
+
29
+ # FPowerKit - A power distribution network calculation component
30
+
31
+ This is a package designed for power distribution network description and solving. Solvers include Newton method, DistFlow and OpenDSS.
32
+
33
+ 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
+
35
+ ```
36
+ @ARTICLE{10970754,
37
+ author={Qian, Tao and Fang, Mingyu and Hu, Qinran and Shao, Chengcheng and Zheng, Junyi},
38
+ journal={IEEE Transactions on Smart Grid},
39
+ title={V2Sim: An Open-Source Microscopic V2G Simulation Platform in Urban Power and Transportation Network},
40
+ year={2025},
41
+ volume={16},
42
+ number={4},
43
+ pages={3167-3178},
44
+ keywords={Vehicle-to-grid;Partial discharges;Microscopy;Batteries;Planning;Discharges (electric);Optimization;Vehicle dynamics;Transportation;Roads;EV charging load simulation;microscopic EV behavior;vehicle-to-grid;charging station fault sensing},
45
+ doi={10.1109/TSG.2025.3560976}}
46
+ ```
47
+
48
+ ### Installation options
49
+ If you want to use different features, install with different command:
50
+
51
+ |Feature|Command|
52
+ |---|---|
53
+ |Only grid description|`pip install fpowerkit`|
54
+ |Y matrix & Newton|`pip install fpowerkit[newton]`|
55
+ |OpenDSS|`pip install fpowerkit[dss]`|
56
+ |DistFlow|`pip install fpowerkit[distflow]`|
57
+ |All|`pip install fpowerkit[full]`|
58
+
59
+ Secondary development on this package requires all features.
60
+
61
+ ### Introduction
62
+ There are 3 modes for this package to work:
63
+
64
+ - Optimal power flow (OPF): Use cvxpy to solve the optimal power flow and determine the output of the generators.
65
+
66
+ - Power flow calculation: Use OpenDSS/Newton-Raphson method to solve the power flow.
67
+
68
+ - Hybrid: Use OPF to determine the initial value, and then use OpenDSS/Newton-Raphson to perform accurate calculation.
69
+
70
+ Please visit https://gitee.com/fmy_xfk/fpowerkit to read the detailed introduction and the usage.
@@ -1,6 +1,19 @@
1
1
  # FPowerKit 配电网运算组件
2
2
  **本仓库已上线PyPI**,您可以通过`pip install fpowerkit`直接以Python包的形式安装使用本仓库的代码!
3
3
 
4
+ ## 安装
5
+ 不同的体验所需的安装命令有所不同:
6
+
7
+ |体验|安装命令|
8
+ |---|---|
9
+ |仅电网描述|`pip install fpowerkit`|
10
+ |导纳矩阵和牛顿法|`pip install fpowerkit[newton]`|
11
+ |OpenDSS求解|`pip install fpowerkit[dss]`|
12
+ |DistFlow模型|`pip install fpowerkit[distflow]`|
13
+ |完整版|`pip install fpowerkit[full]`|
14
+
15
+ 二次开发请使用完整版体验。
16
+
4
17
  ## 简介
5
18
  - FPowerKit是一个配电网求解组件,它包含电网的描述(含母线、发电机、线路、光伏、风机和储能等)和多种内置和外部求解方案:
6
19
  + (内置) 改进DistFlow配电网最优潮流 ([原理介绍](docs/principle.md))
@@ -1,28 +1,6 @@
1
- Metadata-Version: 2.4
2
- Name: fpowerkit
3
- Version: 0.3.3rc0
4
- Summary: A PDN solver with multiple solutions.
5
- Author: fmy_xfk
6
- Classifier: Programming Language :: Python :: 3
7
- Classifier: License :: OSI Approved :: MIT License
8
- Classifier: Operating System :: OS Independent
9
- Requires-Python: >=3.8
10
- Description-Content-Type: text/markdown
11
- License-File: LICENSE
12
- Requires-Dist: feasytools>=0.0.21
13
- Requires-Dist: numpy>=1.19.0
14
- Dynamic: author
15
- Dynamic: classifier
16
- Dynamic: description
17
- Dynamic: description-content-type
18
- Dynamic: license-file
19
- Dynamic: requires-dist
20
- Dynamic: requires-python
21
- Dynamic: summary
22
-
23
1
  # FPowerKit - A power distribution network calculation component
24
2
 
25
- This is a package designed for power distribution network solving.
3
+ This is a package designed for power distribution network description and solving. Solvers include Newton method, DistFlow and OpenDSS.
26
4
 
27
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):
28
6
 
@@ -39,14 +17,26 @@ This package is affiliated to V2Sim, an open-aource microscopic V2G simulation p
39
17
  doi={10.1109/TSG.2025.3560976}}
40
18
  ```
41
19
 
20
+ ### Installation options
21
+ If you want to use different features, install with different command:
22
+
23
+ |Feature|Command|
24
+ |---|---|
25
+ |Only grid description|`pip install fpowerkit`|
26
+ |Y matrix & Newton|`pip install fpowerkit[newton]`|
27
+ |OpenDSS|`pip install fpowerkit[dss]`|
28
+ |DistFlow|`pip install fpowerkit[distflow]`|
29
+ |All|`pip install fpowerkit[full]`|
30
+
31
+ Secondary development on this package requires all features.
32
+
33
+ ### Introduction
42
34
  There are 3 modes for this package to work:
43
35
 
44
36
  - Optimal power flow (OPF): Use cvxpy to solve the optimal power flow and determine the output of the generators.
45
37
 
46
- - Power flow calculation: Use OpenDSS/GridCal/Inner Newton-Raphson method to solve the power flow.
47
-
48
- - Hybrid: Use OPF to determine the initial value, and then use OpenDSS/GridCal/Inner Newton-Raphson to perform accurate calculation.
38
+ - Power flow calculation: Use OpenDSS/Newton-Raphson method to solve the power flow.
49
39
 
50
- Since this package is still under development, the API is unstable and may be changed anytime.
40
+ - Hybrid: Use OPF to determine the initial value, and then use OpenDSS/Newton-Raphson to perform accurate calculation.
51
41
 
52
- Please visit https://gitee.com/fmy_xfk/fpowerkit to read the detailed introduction and the usage.
42
+ Please visit https://gitee.com/fmy_xfk/fpowerkit to read the detailed introduction and the usage.
@@ -0,0 +1,16 @@
1
+ from .bus import *
2
+ from .cases import *
3
+ from .ess import *
4
+ from .gen import *
5
+ from .grid import *
6
+ from .island import *
7
+ from .line import *
8
+ from .pvwind import *
9
+ from .solbase import *
10
+ from .solcmb import *
11
+ from .solcvx import *
12
+ from .soldist import *
13
+ from .soldss import *
14
+ from .solldf import *
15
+ from .solnt import *
16
+ from .utils import *
@@ -1,4 +1,7 @@
1
1
  import math
2
+ from typing import Optional
3
+ from xml.etree.ElementTree import Element
4
+ from feasytools import TimeFunc
2
5
  from .utils import *
3
6
 
4
7
 
@@ -191,4 +194,6 @@ class Bus:
191
194
  unit = ["pu", "pu"]
192
195
  e.append(Func2Elem(self.Pd, "Pd", mul, unit[0]))
193
196
  e.append(Func2Elem(self.Qd, "Qd", mul, unit[1]))
194
- return e
197
+ return e
198
+
199
+ __all__ = ["Bus"]
@@ -354,4 +354,6 @@ class PDNCases:
354
354
  _get_lines(Ub_kV**2/Sb_MVA, _IEEE69_LINE, grid_repeat),
355
355
  _get_gens(default_gen, gen_pos, grid_repeat),
356
356
  [],[]
357
- )
357
+ )
358
+
359
+ __all__ = ["PDNCases"]
@@ -1,5 +1,7 @@
1
- from enum import IntEnum, Enum
2
1
  import math
2
+ from typing import Optional
3
+ from enum import IntEnum, Enum
4
+ from xml.etree.ElementTree import Element
3
5
  from feasytools import RangeList
4
6
  from .utils import *
5
7
 
@@ -119,7 +121,7 @@ class ESS:
119
121
  '''Calculate reactive power'''
120
122
  return P * self.tanPhi
121
123
 
122
- def P_var(self, bank: VarBank) -> Variable:
124
+ def P_var(self, bank: VarBank):
123
125
  '''Return a variable for the power of the ESS. Positive value means charging, negative value means discharging.'''
124
126
  return bank.fvar(f"{self.ID}_P", self, "P", value=self.P)
125
127
 
@@ -307,4 +309,6 @@ class ESS:
307
309
  e.attrib["init_elec"] = str(self._elec*mul) + unit[0]
308
310
  if self._cprice: e.attrib["cprice"] = str(self._cprice*mul) + unit[2]
309
311
  if self._dprice: e.attrib["dprice"] = str(self._dprice*mul) + unit[2]
310
- return e
312
+ return e
313
+
314
+ __all__ = ["ESS", "ESSPolicy", "ESSManualState"]
@@ -1,4 +1,7 @@
1
1
  from copy import deepcopy
2
+ from typing import Optional, Union
3
+ from xml.etree.ElementTree import Element
4
+ from feasytools import TimeFunc
2
5
  from .utils import *
3
6
 
4
7
  NFloatOrFunc = Union[None, float, TimeFunc]
@@ -73,7 +76,7 @@ class Generator:
73
76
  self.CostShadow = None
74
77
  self.active = active
75
78
 
76
- def P_var(self, bank: VarBank, t:int = 0) -> Variable:
79
+ def P_var(self, bank: VarBank, t:int = 0):
77
80
  '''Return a variable for the active power output'''
78
81
  if self.FixedP:
79
82
  raise ValueError("Active power output is fixed, cannot create a variable for it.")
@@ -82,7 +85,7 @@ class Generator:
82
85
  p = self.P(t) if isinstance(self.P, TimeFunc) else self.P
83
86
  return bank.fvar(f"{self.ID}_P", self, "_p", p, lb=pmin, ub=pmax)
84
87
 
85
- def Q_var(self, bank: VarBank, t:int = 0) -> Variable:
88
+ def Q_var(self, bank: VarBank, t:int = 0):
86
89
  if self.FixedQ:
87
90
  raise ValueError("Reactive power output is fixed, cannot create a variable for it.")
88
91
  qmin = self.Qmin(t) if isinstance(self.Qmin, TimeFunc) else self.Qmin
@@ -90,7 +93,7 @@ class Generator:
90
93
  q = self.Q(t) if isinstance(self.Q, TimeFunc) else self.Q
91
94
  return bank.fvar(f"{self.ID}_Q", self, "_q", q, lb=qmin, ub=qmax)
92
95
 
93
- def active_var(self, bank: VarBank) -> Variable:
96
+ def active_var(self, bank: VarBank):
94
97
  if self.FixedP or self.FixedQ:
95
98
  raise ValueError("Active or reactive power output is fixed, cannot create an active variable for it.")
96
99
  return bank.bvar(f"{self.ID}_active", self, "active", True)
@@ -300,4 +303,6 @@ class GeneratorModel:
300
303
  e.append(Func2Elem(self.CostA, "CostA"))
301
304
  e.append(Func2Elem(self.CostB, "CostB"))
302
305
  e.append(Func2Elem(self.CostC, "CostC"))
303
- return e
306
+ return e
307
+
308
+ __all__ = ["Generator", "GeneratorModel"]
@@ -1,11 +1,10 @@
1
- from collections import deque
2
- from enum import IntEnum
3
1
  import gzip
4
- from xml.etree.ElementTree import ElementTree
5
2
  import zipfile
6
- from typing import Iterable
7
-
8
- import numpy as np
3
+ from xml.etree.ElementTree import Element, ElementTree
4
+ from enum import IntEnum
5
+ from typing import Iterable, Optional
6
+ from feasytools import ConstFunc
7
+ from .utils import *
9
8
  from .bus import *
10
9
  from .line import *
11
10
  from .gen import *
@@ -445,8 +444,9 @@ class Grid:
445
444
  raise ValueError(f"Unknown XML node: {e.tag}")
446
445
  return Grid(Sb, Ub, buses, lines, gens, pvws, esss, cp, dp, holdShadowPrice)
447
446
 
448
- def YMat(self) -> 'np.ndarray':
449
- '''Return the admittance matrix of the grid'''
447
+ def YMat(self):
448
+ '''(NumPy required) Return the admittance matrix of the grid'''
449
+ import numpy as np
450
450
  n = len(self._buses)
451
451
  Y = np.zeros((n, n), dtype=complex)
452
452
  for l in self.ActiveLines:
@@ -523,3 +523,5 @@ class Grid:
523
523
  bn, p, q = ln.strip().split(',')
524
524
  self.Bus(bn).Pd = ConstFunc(float(p) / self.Sb)
525
525
  self.Bus(bn).Qd = ConstFunc(float(q) / self.Sb)
526
+
527
+ __all__ = ["Grid", "PQSaveMode", "USaveMode", "ZSaveMode", "BusID", "LineID"]
@@ -1,5 +1,7 @@
1
1
  from collections import deque
2
+ from enum import IntEnum
2
3
  from itertools import chain
4
+ from typing import Any, Iterable
3
5
  from .grid import *
4
6
 
5
7
  class IslandResult(IntEnum):
@@ -75,9 +77,10 @@ class Island:
75
77
  def ESSItems(self):
76
78
  for e in self.ESSs:
77
79
  yield e, self.grid.ESS(e)
78
-
79
- def YMat(self) -> 'tuple[dict[str,int], np.ndarray]':
80
- '''Return the admittance matrix of the grid'''
80
+
81
+ def YMat(self) -> 'tuple[dict[str,int], Any]':
82
+ '''(NumPy required) Return the admittance matrix of the grid'''
83
+ import numpy as np
81
84
  n = len(self.Buses)
82
85
  bus_dict = {b: i for i, b in enumerate(self.Buses)}
83
86
  Y = np.zeros((n, n), dtype=complex)
@@ -1,4 +1,6 @@
1
1
  import math
2
+ from typing import Optional
3
+ from xml.etree.ElementTree import Element
2
4
  from .utils import *
3
5
 
4
6
 
@@ -31,25 +33,25 @@ class Line:
31
33
  self.L = length_km
32
34
  self.active = active
33
35
 
34
- def active_var(self, bank: VarBank) -> Variable:
36
+ def active_var(self, bank: VarBank):
35
37
  '''Return a variable indicating whether the line is active'''
36
38
  return bank.bvar(f"{self.ID}_active", self, "active", value=self.active)
37
39
 
38
- def I_var(self, bank: VarBank) -> Variable:
40
+ def I_var(self, bank: VarBank):
39
41
  '''Return a variable for the current of the line'''
40
42
  return bank.fvar(f"{self.ID}_I", self, "I", value=self.I, nonneg=True, lb=0.0, ub=self.max_I)
41
43
 
42
- def I2_var(self, bank: VarBank) -> Variable:
44
+ def I2_var(self, bank: VarBank):
43
45
  '''Return a variable for the square of the current of the line'''
44
46
  i = self.I if self.I is not None else 0.0
45
47
  return bank.fvar(f"{self.ID}_I2", self, "I", value=i**2, nonneg=True,
46
48
  lb=0.0, ub=self.max_I**2, reflect=lambda x: math.sqrt(x))
47
49
 
48
- def P_var(self, bank: VarBank) -> Variable:
50
+ def P_var(self, bank: VarBank):
49
51
  '''Return a variable for the real power flow of the line'''
50
52
  return bank.fvar(f"{self.ID}_P", self, "P", value=self.P)
51
53
 
52
- def Q_var(self, bank: VarBank) -> Variable:
54
+ def Q_var(self, bank: VarBank):
53
55
  '''Return a variable for the reactive power flow of the line'''
54
56
  return bank.fvar(f"{self.ID}_Q", self, "Q", value=self.Q)
55
57
 
@@ -122,5 +124,7 @@ class Line:
122
124
  "R": f"{self.R*Zb_Ohm:.6f}ohm" if Zb_Ohm is not None else f"{self.R:.8f}pu",
123
125
  "X": f"{self.X*Zb_Ohm:.6f}ohm" if Zb_Ohm is not None else f"{self.X:.8f}pu",
124
126
  "MaxIkA": str(self.max_I),
125
- "Length_km": str(self.L)
126
- })
127
+ "Length_km": str(self.L) if self.L is not None else "-1"
128
+ })
129
+
130
+ __all__ = ['Line']
@@ -1,4 +1,6 @@
1
1
  import math
2
+ from xml.etree.ElementTree import Element
3
+ from typing import Optional
2
4
  from .utils import *
3
5
 
4
6
  class PVWind:
@@ -169,4 +171,5 @@ class PVWind:
169
171
  e.attrib["cc"] = str(self.CC*mul) + unit[1]
170
172
 
171
173
  return e
172
-
174
+
175
+ __all__ = ['PVWind']
@@ -82,4 +82,6 @@ class SolverBase(ABC):
82
82
  @abstractmethod
83
83
  def solve_island(self, i:int, island:Island, _t:int, /, **kwargs) -> 'tuple[IslandResult, float]':
84
84
  '''Solve the island'''
85
- raise NotImplementedError
85
+ raise NotImplementedError
86
+
87
+ __all__ = ['SolverBase', 'GridSolveResult', 'DEFAULT_SAVETO']
@@ -1,8 +1,8 @@
1
1
  from enum import Enum
2
2
  from typing import Union, Iterable
3
- from .grid import Grid
4
- from .solbase import DEFAULT_SAVETO, GridSolveResult, SolverBase
5
3
  from warnings import warn
4
+ from .grid import Grid
5
+ from .solbase import *
6
6
 
7
7
  class Estimator(Enum):
8
8
  DistFlow = 'DistFlow'
@@ -1,6 +1,5 @@
1
1
  from abc import abstractmethod
2
- from typing import List, Optional, Tuple
3
- import cvxpy as cp
2
+ from typing import Any, List, Optional, Tuple
4
3
  from .island import Island, IslandResult
5
4
  from .utils import VarBank
6
5
  from .grid import Grid
@@ -12,13 +11,13 @@ class ManualSolver(SolverBase):
12
11
  """
13
12
  def __init__(self, grid:Grid, eps:float = 1e-6, max_iter:int = 1000, *,
14
13
  default_saveto:str = DEFAULT_SAVETO, bank: Optional[VarBank] = None,
15
- solver = cp.ECOS):
14
+ solver = "ECOS"):
16
15
  super().__init__(grid, eps, max_iter, default_saveto = default_saveto)
17
16
  self.bank = bank if bank is not None else VarBank()
18
17
  self.default_sovler = solver # Default solver, can be overridden in solve method
19
18
 
20
19
  @abstractmethod
21
- def proc_solution(self, i:int, _t:int, bank: VarBank, grid: Grid, island:Island) -> Tuple[List[cp.Constraint], cp.Expression]:
20
+ def proc_solution(self, i:int, _t:int, bank: VarBank, grid: Grid, island:Island) -> Tuple[List, Any]:
22
21
  """
23
22
  Process the solution for the island.
24
23
  i: Index of the island in the grid
@@ -26,7 +25,7 @@ class ManualSolver(SolverBase):
26
25
  bank: Variable bank to store the variables and implict constraints
27
26
  grid: The grid object
28
27
  island: The island to solve
29
- Returns a tuple of constraints and objective expression.
28
+ Returns: (List of constraints, objective expression)
30
29
  The objective will be minimized.
31
30
  """
32
31
  raise NotImplementedError
@@ -38,6 +37,10 @@ class ManualSolver(SolverBase):
38
37
 
39
38
  def solve_island(self, i:int, island:Island, _t:int, /, **kwargs) -> Tuple[IslandResult, float]:
40
39
  """Solve the island"""
40
+ try:
41
+ import cvxpy as cp
42
+ except ImportError:
43
+ raise ImportError("cvxpy or ecos is not installed. Please install them using 'pip install cvxpy ecos'")
41
44
  cons, obj = self.proc_solution(i, _t, self.bank, self._g, island)
42
45
  for cname, c in self.bank._autocons.items():
43
46
  if island.hasName(cname):
@@ -1,9 +1,11 @@
1
+ import math
2
+ import warnings
1
3
  from itertools import chain
2
4
  from pathlib import Path
3
5
  from typing import Optional, Union
4
6
  from dataclasses import dataclass
5
- import math
6
- import warnings
7
+ from feasytools import TimeFunc
8
+ from .utils import FloatVar
7
9
  from .solbase import *
8
10
  from .island import *
9
11
 
@@ -112,10 +114,10 @@ class DistFlowSolver(SolverBase):
112
114
  else:
113
115
  return GridSolveResult.PartialOK, val
114
116
 
115
- def __chkv(self, d: Union[None, np.ndarray]) -> float:
116
- assert d is not None, "Value is None"
117
+ def __chkv(self, d: Union[None, Any]) -> float:
118
+ import numpy as np
117
119
  assert isinstance(d, (np.ndarray, np.floating, float)), f"Value is {type(d)}"
118
- ret = d.item()
120
+ ret = d.item() if isinstance(d, np.ndarray) else d
119
121
  assert isinstance(ret, float), f"Value is not a float: {type(ret)}"
120
122
  assert ret != float('inf'), "Value is inf"
121
123
  assert ret != float('-inf'), "Value is -inf"
@@ -1,5 +1,9 @@
1
- from fpowerkit.grid import Grid
1
+ import math
2
+ from typing import Iterable, Union
3
+ from feasytools import TimeFunc
4
+ from .grid import Grid
2
5
  from .solbase import *
6
+ from .island import Island, IslandResult
3
7
 
4
8
  def _convert(il:Island, t:int, source_bus:str):
5
9
  try:
@@ -1,7 +1,4 @@
1
- from typing import List, Optional, Tuple
2
- import cvxpy as cp
3
- from cvxpy import Constraint
4
- from cvxpy import Expression
1
+ from typing import Any, List, Optional, Tuple
5
2
  from .solbase import DEFAULT_SAVETO, GridSolveResult
6
3
  from .grid import Grid
7
4
  from .island import Island
@@ -12,13 +9,17 @@ from .solcvx import ManualSolver
12
9
  class LinDistFlowSolver(ManualSolver):
13
10
  def __init__(self, grid:Grid, eps:float = 1e-6, max_iter:int = 1000, *,
14
11
  default_saveto:str = DEFAULT_SAVETO, bank: Optional[VarBank] = None,
15
- solver = cp.ECOS_BB):
12
+ solver = "ECOS_BB"):
16
13
  super().__init__(grid, eps, max_iter, default_saveto=default_saveto, bank=bank, solver=solver)
17
14
 
18
15
  def solve(self, _t:int, /, *, timeout_s: float = 1) -> Tuple[GridSolveResult, float]:
19
16
  return super().solve(_t, timeout_s=timeout_s, calc_line=False)
20
17
 
21
- def proc_solution(self, i: int, _t:int, bank: VarBank, grid: Grid, island: Island) -> Tuple[List[Constraint], Expression]:
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'.")
22
23
  cons = []
23
24
  obj = 0
24
25
  # Bind GEN vars to Bus
@@ -1,6 +1,10 @@
1
- import numpy as np
2
1
  import math
2
+ from typing import Any
3
+ from feasytools import TimeFunc
4
+ from enum import IntEnum
3
5
  from dataclasses import dataclass
6
+ from .grid import BusID, Grid
7
+ from .island import Island, IslandResult
4
8
  from .solbase import *
5
9
 
6
10
  class BusType(IntEnum):
@@ -15,8 +19,8 @@ class _NRProblem:
15
19
  Ps: 'list[float]'
16
20
  Qs: 'list[float]'
17
21
  bus_dict: 'dict[str, int]'
18
- G: 'np.ndarray'
19
- B: 'np.ndarray'
22
+ G: Any # np.ndarray 2D
23
+ B: Any # np.ndarray 2D
20
24
  V: 'list[float]'
21
25
  theta: 'list[float]'
22
26
 
@@ -82,6 +86,10 @@ def _presolve(il:Island, _t:int):
82
86
 
83
87
  def _solve(prb: _NRProblem, max_iter:int = 100, eps:float = 1e-6):
84
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'.")
85
93
  G = prb.G
86
94
  B = prb.B
87
95
  V = prb.V
@@ -1,4 +1,3 @@
1
- from cvxpy import Variable, Constraint
2
1
  from typing import Callable, Optional, Tuple, Union, List, Dict
3
2
  from feasytools import TimeFunc, SegFunc, ConstFunc
4
3
  from xml.etree.ElementTree import Element
@@ -13,12 +12,20 @@ FloatVals = Union[int, float]
13
12
 
14
13
  class VarBank:
15
14
  def __init__(self):
15
+ try:
16
+ from cvxpy import Variable, Constraint
17
+ except ImportError:
18
+ raise ImportError("cvxpy is required for VarBank. Please install it via 'pip install cvxpy'.")
16
19
  self._vars:Dict[str, Tuple[object, str, Variable, Optional[Callable]]] = {}
17
20
  self._autocons:Dict[str, Constraint] = {}
18
21
 
19
22
  def __var(self, name:str, obj: object, attr: str, value = None, boolean:bool = False, integer:bool = False,
20
23
  nonneg:bool = False, lb: Optional[float] = None, ub: Optional[float] = None,
21
- reflect:Optional[Callable] = None) -> Variable:
24
+ reflect:Optional[Callable] = None):
25
+ try:
26
+ from cvxpy import Variable
27
+ except ImportError:
28
+ raise ImportError("cvxpy is required for VarBank. Please install it via 'pip install cvxpy'.")
22
29
  if name in self._vars:
23
30
  return self._vars[name][2]
24
31
  if hasattr(obj, attr):
@@ -37,16 +44,16 @@ class VarBank:
37
44
  self._autocons[name + "_ub"] = (v <= ub)
38
45
  return v
39
46
  @property
40
- def variables(self) -> Dict[str, Variable]:
47
+ def variables(self):
41
48
  '''Get all variables in the bank.'''
42
49
  return {name: var[2] for name, var in self._vars.items()}
43
50
 
44
51
  @property
45
- def constraints(self) -> Dict[str, Constraint]:
52
+ def constraints(self):
46
53
  '''Get all constraints in the bank.'''
47
54
  return self._autocons
48
55
 
49
- def __getitem__(self, name: str) -> Variable:
56
+ def __getitem__(self, name: str):
50
57
  '''Get a variable by name.'''
51
58
  if name in self._vars:
52
59
  return self._vars[name][2]
@@ -55,13 +62,13 @@ class VarBank:
55
62
 
56
63
  def fvar(self, name:str, obj: object, attr: str, value:Optional[float] = None,
57
64
  nonneg:bool = False, lb: Optional[float] = None, ub: Optional[float] = None,
58
- reflect:Optional[Callable[[float], float]] = None) -> Variable:
65
+ reflect:Optional[Callable[[float], float]] = None):
59
66
  '''Create a variable with the given name and attributes.'''
60
67
  return self.__var(name, obj, attr, value, False, False, nonneg, lb, ub, reflect)
61
68
 
62
69
  def ivar(self, name:str, obj: object, attr: str, value:Optional[int] = None,
63
70
  nonneg:bool = False, lb: Optional[float] = None, ub: Optional[float] = None,
64
- reflect:Optional[Callable[[int], int]] = None) -> Variable:
71
+ reflect:Optional[Callable[[int], int]] = None):
65
72
  '''Create an integer variable with the given name and attributes.'''
66
73
  return self.__var(name, obj, attr, value, False, True, nonneg, lb, ub, reflect)
67
74
 
@@ -212,4 +219,20 @@ def ReadNFloatLike(e: Optional[Element], sb_mva:float, ub_kv:float) -> NFloatLik
212
219
  def ReadFloatLike(e: Optional[Element], sb_mva:float, ub_kv:float) -> FloatLike:
213
220
  r = ReadNFloatLike(e, sb_mva, ub_kv)
214
221
  assert r is not None
215
- return r
222
+ return r
223
+
224
+ __all__ = [
225
+ 'VarBank',
226
+ 'Float2Func',
227
+ 'Func2Elem',
228
+ 'FVstr',
229
+ 'ReadVal',
230
+ 'ReadConst',
231
+ 'ReadFloatLike',
232
+ 'ReadNFloatLike',
233
+ 'NFloat',
234
+ 'FloatLike',
235
+ 'NFloatLike',
236
+ 'FloatVals',
237
+ 'FloatVar'
238
+ ]
@@ -0,0 +1,90 @@
1
+ import sys
2
+ from fpowerkit import *
3
+ import argparse
4
+
5
+
6
+ if __name__=="__main__":
7
+ parser = argparse.ArgumentParser(description='Gurobi DistFlow Model Solver')
8
+ parser.add_argument('-g',type=str,required=True,metavar="grid",help="path to a grid case zipfile")
9
+ parser.add_argument('-o',type=str,required=False,metavar="output",help="Output file for the result", default="")
10
+ parser.add_argument('-m',type=str,required=False,metavar='method',help="Newton, DistFlow, GridCal, or Combined", default="Combined")
11
+ parser.add_argument('-b',type=int,required=False,metavar='begin',help="Solver begin time", default=0)
12
+ parser.add_argument('-e',type=int,required=False,metavar='end',help="Solver end time", default=0)
13
+ parser.add_argument('-s',type=int,required=False,metavar='step',help="Solver time step", default=300)
14
+ parser.add_argument('-l',type=str,required=False,metavar='log',help="Items to be written in the log file", default="bus, gen, line, pvwind, ess")
15
+ parser.add_argument('-sb',type=str,metavar='source_bus',help="Source bus/Slack bus ID for OpenDSS/GridCal solver", default="")
16
+ opt = parser.parse_args()
17
+ gr = Grid.fromFile(opt.g)
18
+ if opt.o == "":
19
+ output = sys.stdout
20
+ req_close = False
21
+ print("Grid structure:")
22
+ print(gr)
23
+ else:
24
+ output = open(opt.o,"w")
25
+ req_close = True
26
+ if opt.m == "DistFlow":
27
+ svr = DistFlowSolver(gr)
28
+ elif opt.m == "Newton":
29
+ svr = NewtonSolver(gr)
30
+ elif opt.m == "OpenDSS":
31
+ svr = OpenDSSSolver(gr, source_bus=opt.sb.split(','))
32
+ elif opt.m == "Combined":
33
+ svr = CombinedSolver(gr, source_bus=opt.sb)
34
+ elif opt.m == "LinDistFlow":
35
+ svr = LinDistFlowSolver(gr)
36
+ else:
37
+ raise ValueError(f"Invalid sovler: {opt.m}")
38
+ def _chk(x):
39
+ if x is None: return "None"
40
+ else: return f"{x:.4f}"
41
+ logs = [x.strip().lower() for x in opt.l.split(',')]
42
+ for t in range(opt.b,opt.e+1,opt.s):
43
+ print(f"Time {t}:", file=output)
44
+ ret,val = svr.solve(t)
45
+ if ret:
46
+ print(f"Obj = {val:.6f}", file=output)
47
+ if "bus" in logs:
48
+ if opt.m=='DistFlow' or opt.m=='LinDistFlow':
49
+ print("BusID\tV/pu", file=output)
50
+ for bus in gr.Buses:
51
+ print(f"{bus.ID:5}\t{_chk(bus.V)}", file=output)
52
+ else:
53
+ print("BusID\tV/pu\tθ/rad", file=output)
54
+ for bus in gr.Buses:
55
+ print(f"{bus.ID:5}\t{_chk(bus.V)}\t{_chk(bus.theta)}", file=output)
56
+ if "line" in logs:
57
+ print("LineID\tI/kA \tP/pu \tQ/pu ", file=output)
58
+ for line in gr.Lines:
59
+ i = _chk(line.I*gr.Ib) if line.I is not None else "None"
60
+ print(f"{line.ID:6}\t{i}\t{_chk(line.P)}\t{_chk(line.Q)}", file=output)
61
+ if isinstance(svr,DistFlowSolver) and len(svr.OverflowLines)>0:
62
+ ofl = ','.join(map(str,svr.OverflowLines))
63
+ print(f"Overflow lines: {ofl}", file=output)
64
+ if opt.m=='DistFlow':
65
+ if "gen" in logs:
66
+ print(f"GenID\tP/pu \tQ/pu ", file=output)
67
+ for gen in gr.Gens:
68
+ p = gen.P(t) if isinstance(gen.P, TimeFunc) else gen.P
69
+ q = gen.Q(t) if isinstance(gen.Q, TimeFunc) else gen.Q
70
+ print(f"{gen.ID:5}\t{_chk(p)}\t{_chk(q)}", file=output)
71
+ if "pvwind" in logs:
72
+ print("PVWID\tP/pu \tQ/pu \tCR/% ", file=output)
73
+ for pvw in gr.PVWinds:
74
+ p = pvw.Pr
75
+ q = pvw.Qr
76
+ cr = pvw.CR
77
+ cr_str = f"{cr*100:.2f}%" if cr is not None else "None"
78
+ print(f"{pvw.ID:5}\t{_chk(p)}\t{_chk(q)}\t{cr_str}", file=output)
79
+ if "ess" in logs:
80
+ print("ESSID\tP/pu \tQ/pu \tSOC/% \tElec/puh", file=output)
81
+ for ess in gr.ESSs:
82
+ p = ess.P
83
+ q = ess.Q
84
+ soc = ess.SOC
85
+ elec = ess._elec
86
+ print(f"{ess.ID:5}\t{p:.4f}\t{q:.4f}\t{soc*100:.2f}%\t{elec:.4f}", file=output)
87
+ gr.ApplyAllESS(opt.s)
88
+ else:
89
+ print("Fail", file=output)
90
+ if req_close: output.close()
@@ -0,0 +1,51 @@
1
+ [build-system]
2
+ requires = ["hatchling"]
3
+ build-backend = "hatchling.build"
4
+
5
+ [tool.hatch.build]
6
+ exclude = [
7
+ "/.*",
8
+ "/docs",
9
+ "/test",
10
+ "/cases",
11
+ ]
12
+
13
+ [project]
14
+ name = "fpowerkit"
15
+ version = "0.3.4"
16
+ requires-python = ">=3.8"
17
+ description = "A PDN solver with multiple solutions."
18
+ readme = "desc.md"
19
+ license = "MIT"
20
+ license-files = ["LICENSE"]
21
+ classifiers = [
22
+ "Programming Language :: Python :: 3",
23
+ "License :: OSI Approved :: MIT License",
24
+ "Operating System :: OS Independent"
25
+ ]
26
+ dependencies = [
27
+ "feasytools>=0.0.21",
28
+ ]
29
+ authors = [
30
+ {name = "fmy-xfk"},
31
+ ]
32
+
33
+ [project.optional-dependencies]
34
+ full = [
35
+ "numpy>=1.19.0",
36
+ "cvxpy",
37
+ "ecos",
38
+ "py_dss_interface",
39
+ ]
40
+ distflow = [
41
+ "numpy>=1.19.0",
42
+ "cvxpy",
43
+ "ecos",
44
+ ]
45
+ dss = [
46
+ "numpy>=1.19.0",
47
+ "py_dss_interface",
48
+ ]
49
+ newton = [
50
+ "numpy>=1.19.0",
51
+ ]
@@ -0,0 +1,32 @@
1
+ import os
2
+
3
+ def compare(file1:str, file2:str):
4
+ with open(file1) as f1, open(file2) as f2:
5
+ lines1 = f1.readlines()
6
+ lines2 = f2.readlines()
7
+ i = 0
8
+ cnt = 0
9
+ for a, b in zip(lines1, lines2):
10
+ a = a.strip()
11
+ b = b.strip()
12
+ i += 1
13
+ if abs(float(a) - float(b)) < 1e-5: continue
14
+ print(f"Diff @ L{i}", a, b)
15
+ cnt += 1
16
+ print(f"Total {cnt} diffs")
17
+ return cnt
18
+
19
+ if __name__ == "__main__":
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
+ print("33base DistFlow")
24
+ os.system('python main.py -g cases/33base.xml -o test/33base_d.out -m DistFlow')
25
+ 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')
@@ -1,8 +0,0 @@
1
- from .grid import *
2
- from .solbase import *
3
- from .solnt import *
4
- from .soldist import *
5
- from .soldss import *
6
- from .solcmb import *
7
- from .solldf import *
8
- from .cases import PDNCases
@@ -1,25 +0,0 @@
1
- LICENSE
2
- README.md
3
- setup.py
4
- fpowerkit/__init__.py
5
- fpowerkit/bus.py
6
- fpowerkit/cases.py
7
- fpowerkit/ess.py
8
- fpowerkit/gen.py
9
- fpowerkit/grid.py
10
- fpowerkit/island.py
11
- fpowerkit/line.py
12
- fpowerkit/pvwind.py
13
- fpowerkit/solbase.py
14
- fpowerkit/solcmb.py
15
- fpowerkit/solcvx.py
16
- fpowerkit/soldist.py
17
- fpowerkit/soldss.py
18
- fpowerkit/solldf.py
19
- fpowerkit/solnt.py
20
- fpowerkit/utils.py
21
- fpowerkit.egg-info/PKG-INFO
22
- fpowerkit.egg-info/SOURCES.txt
23
- fpowerkit.egg-info/dependency_links.txt
24
- fpowerkit.egg-info/requires.txt
25
- fpowerkit.egg-info/top_level.txt
@@ -1,2 +0,0 @@
1
- feasytools>=0.0.21
2
- numpy>=1.19.0
@@ -1 +0,0 @@
1
- fpowerkit
@@ -1,4 +0,0 @@
1
- [egg_info]
2
- tag_build =
3
- tag_date = 0
4
-
@@ -1,21 +0,0 @@
1
- from setuptools import setup, find_packages
2
-
3
- with open("desc.md", "r", encoding="utf8") as f:
4
- long_description = f.read()
5
-
6
- setup(
7
- name="fpowerkit",
8
- version="0.3.3rc0",
9
- author="fmy_xfk",
10
- packages=find_packages(),
11
- description="A PDN solver with multiple solutions.",
12
- long_description=long_description,
13
- long_description_content_type="text/markdown",
14
- classifiers=[
15
- "Programming Language :: Python :: 3",
16
- "License :: OSI Approved :: MIT License",
17
- "Operating System :: OS Independent",
18
- ],
19
- python_requires=">=3.8",
20
- install_requires=["feasytools>=0.0.21", "numpy>=1.19.0"],
21
- )
File without changes