fpowerkit 0.3.1__tar.gz → 0.3.3rc0__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 (27) hide show
  1. {fpowerkit-0.3.1 → fpowerkit-0.3.3rc0}/PKG-INFO +7 -5
  2. {fpowerkit-0.3.1 → fpowerkit-0.3.3rc0}/README.md +5 -5
  3. {fpowerkit-0.3.1 → fpowerkit-0.3.3rc0}/fpowerkit/__init__.py +1 -0
  4. {fpowerkit-0.3.1 → fpowerkit-0.3.3rc0}/fpowerkit/bus.py +46 -5
  5. {fpowerkit-0.3.1 → fpowerkit-0.3.3rc0}/fpowerkit/ess.py +52 -5
  6. {fpowerkit-0.3.1 → fpowerkit-0.3.3rc0}/fpowerkit/gen.py +26 -1
  7. {fpowerkit-0.3.1 → fpowerkit-0.3.3rc0}/fpowerkit/island.py +9 -1
  8. {fpowerkit-0.3.1 → fpowerkit-0.3.3rc0}/fpowerkit/line.py +22 -0
  9. {fpowerkit-0.3.1 → fpowerkit-0.3.3rc0}/fpowerkit/pvwind.py +18 -2
  10. {fpowerkit-0.3.1 → fpowerkit-0.3.3rc0}/fpowerkit/solbase.py +2 -2
  11. {fpowerkit-0.3.1 → fpowerkit-0.3.3rc0}/fpowerkit/solcmb.py +5 -3
  12. fpowerkit-0.3.3rc0/fpowerkit/solcvx.py +55 -0
  13. {fpowerkit-0.3.1 → fpowerkit-0.3.3rc0}/fpowerkit/soldist.py +3 -3
  14. fpowerkit-0.3.3rc0/fpowerkit/solldf.py +90 -0
  15. {fpowerkit-0.3.1 → fpowerkit-0.3.3rc0}/fpowerkit/utils.py +73 -1
  16. {fpowerkit-0.3.1 → fpowerkit-0.3.3rc0}/fpowerkit.egg-info/PKG-INFO +7 -5
  17. {fpowerkit-0.3.1 → fpowerkit-0.3.3rc0}/fpowerkit.egg-info/SOURCES.txt +2 -0
  18. {fpowerkit-0.3.1 → fpowerkit-0.3.3rc0}/setup.py +1 -1
  19. {fpowerkit-0.3.1 → fpowerkit-0.3.3rc0}/LICENSE +0 -0
  20. {fpowerkit-0.3.1 → fpowerkit-0.3.3rc0}/fpowerkit/cases.py +0 -0
  21. {fpowerkit-0.3.1 → fpowerkit-0.3.3rc0}/fpowerkit/grid.py +0 -0
  22. {fpowerkit-0.3.1 → fpowerkit-0.3.3rc0}/fpowerkit/soldss.py +0 -0
  23. {fpowerkit-0.3.1 → fpowerkit-0.3.3rc0}/fpowerkit/solnt.py +0 -0
  24. {fpowerkit-0.3.1 → fpowerkit-0.3.3rc0}/fpowerkit.egg-info/dependency_links.txt +0 -0
  25. {fpowerkit-0.3.1 → fpowerkit-0.3.3rc0}/fpowerkit.egg-info/requires.txt +0 -0
  26. {fpowerkit-0.3.1 → fpowerkit-0.3.3rc0}/fpowerkit.egg-info/top_level.txt +0 -0
  27. {fpowerkit-0.3.1 → fpowerkit-0.3.3rc0}/setup.cfg +0 -0
@@ -1,6 +1,6 @@
1
- Metadata-Version: 2.2
1
+ Metadata-Version: 2.4
2
2
  Name: fpowerkit
3
- Version: 0.3.1
3
+ Version: 0.3.3rc0
4
4
  Summary: A PDN solver with multiple solutions.
5
5
  Author: fmy_xfk
6
6
  Classifier: Programming Language :: Python :: 3
@@ -15,6 +15,7 @@ Dynamic: author
15
15
  Dynamic: classifier
16
16
  Dynamic: description
17
17
  Dynamic: description-content-type
18
+ Dynamic: license-file
18
19
  Dynamic: requires-dist
19
20
  Dynamic: requires-python
20
21
  Dynamic: summary
@@ -31,10 +32,11 @@ This package is affiliated to V2Sim, an open-aource microscopic V2G simulation p
31
32
  journal={IEEE Transactions on Smart Grid},
32
33
  title={V2Sim: An Open-Source Microscopic V2G Simulation Platform in Urban Power and Transportation Network},
33
34
  year={2025},
34
- pages={1-1},
35
- 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},
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},
36
39
  doi={10.1109/TSG.2025.3560976}}
37
-
38
40
  ```
39
41
 
40
42
  There are 3 modes for this package to work:
@@ -3,7 +3,7 @@
3
3
 
4
4
  ## 简介
5
5
  - FPowerKit是一个配电网求解组件,它包含电网的描述(含母线、发电机、线路、光伏、风机和储能等)和多种内置和外部求解方案:
6
- + (内置) 改进DistFlow配电网最优潮流
6
+ + (内置) 改进DistFlow配电网最优潮流 ([原理介绍](docs/principle.md))
7
7
  + (内置) Newton-Raphson潮流计算
8
8
  + (外接) OpenDSS配电网潮流计算
9
9
  + 最优潮流+潮流计算核验的混合方案
@@ -30,16 +30,16 @@ grid_obj69 = PDNCases.IEEE69()
30
30
 
31
31
  如果你正在使用本项目中的**改进配电网DistFlow模型**,请引用[V2Sim正式版论文](https://ieeexplore.ieee.org/document/10970754):
32
32
 
33
- ```
34
33
  @ARTICLE{10970754,
35
34
  author={Qian, Tao and Fang, Mingyu and Hu, Qinran and Shao, Chengcheng and Zheng, Junyi},
36
35
  journal={IEEE Transactions on Smart Grid},
37
36
  title={V2Sim: An Open-Source Microscopic V2G Simulation Platform in Urban Power and Transportation Network},
38
37
  year={2025},
39
- pages={1-1},
40
- 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},
38
+ volume={16},
39
+ number={4},
40
+ pages={3167-3178},
41
+ 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},
41
42
  doi={10.1109/TSG.2025.3560976}}
42
-
43
43
  ```
44
44
 
45
45
  IEEE33和IEEE69节点的配网数据从公开渠道收集。除配网数据以外,本仓库代码均遵循LGPL3.0协议使用。
@@ -4,4 +4,5 @@ from .solnt import *
4
4
  from .soldist import *
5
5
  from .soldss import *
6
6
  from .solcmb import *
7
+ from .solldf import *
7
8
  from .cases import PDNCases
@@ -10,7 +10,7 @@ class Bus:
10
10
  Lon: NFloat
11
11
 
12
12
  def __init__(self, id: str, pd_pu: FloatLike, qd_pu: FloatLike, lat: NFloat = None, lon: NFloat = None,
13
- v_pu: NFloat = None, min_v_pu: float = 0.0, max_v_pu: float = float('inf')):
13
+ v_pu: NFloat = None, min_v_pu: float = 0.0, max_v_pu: float = float('inf'), theta: NFloat = None):
14
14
  '''
15
15
  Initialize
16
16
  id: Bus ID
@@ -24,7 +24,7 @@ class Bus:
24
24
  '''
25
25
  self._id = id
26
26
  self._v = v_pu
27
- self._fixed_v = self.V is not None
27
+ self._fixed_v = v_pu is not None
28
28
  self._minv = min_v_pu
29
29
  self._maxv = max_v_pu
30
30
  self.Pd = Float2Func(pd_pu)
@@ -32,8 +32,26 @@ class Bus:
32
32
  self.ShadowPrice = None
33
33
  self.Lat = lat
34
34
  self.Lon = lon
35
- self.theta = 0.0
35
+ self._t = theta
36
+ self._fixed_t = self._t is not None
36
37
 
38
+ def V_var(self, bank: VarBank):
39
+ if self.FixedV:
40
+ raise ValueError("Voltage is fixed, cannot create a variable for it.")
41
+ return bank.fvar(f"{self.ID}_V", self, "_v", self.V, nonneg=True, lb=self.MinV, ub=self.MaxV)
42
+
43
+ def V2_var(self, bank: VarBank):
44
+ if self.FixedV:
45
+ raise ValueError("Voltage is fixed, cannot create a variable for it.")
46
+ v = self.V if self.V is not None else 1.0
47
+ return bank.fvar(f"{self.ID}_V2", self, "_v", v**2, nonneg=True,
48
+ lb=self.MinV**2, ub=self.MaxV**2, reflect=lambda x: math.sqrt(x))
49
+
50
+ def theta_var(self, bank: VarBank):
51
+ if self.FixedTheta:
52
+ raise ValueError("Voltage angle is fixed, cannot create a variable for it.")
53
+ return bank.fvar(f"{self.ID}_theta", self, "_theta", self._t)
54
+
37
55
  @property
38
56
  def V(self) -> FloatVar:
39
57
  '''Voltage, pu'''
@@ -41,11 +59,19 @@ class Bus:
41
59
  @V.setter
42
60
  def V(self, v: float):
43
61
  self._v = v
62
+
63
+ @property
64
+ def theta(self) -> float:
65
+ '''Voltage angle, rad'''
66
+ return self._t if self._t is not None else 0.0
67
+ @theta.setter
68
+ def theta(self, t: float):
69
+ self._t = t
44
70
 
45
71
  @property
46
72
  def V_cpx(self) -> Optional[complex]:
47
- if self._v is None: return None
48
- return self._v * math.cos(self.theta) + 1j * self._v * math.sin(self.theta)
73
+ if self._v is None or self._t is None: return None
74
+ return self._v * math.cos(self._t) + 1j * self._v * math.sin(self._t)
49
75
 
50
76
  @property
51
77
  def FixedV(self) -> bool:
@@ -61,6 +87,21 @@ class Bus:
61
87
  self._v = None
62
88
  self._fixed_v = False
63
89
 
90
+ @property
91
+ def FixedTheta(self) -> bool:
92
+ '''Whether the voltage angle is fixed'''
93
+ return self._fixed_t
94
+
95
+ def fixTheta(self, theta: float):
96
+ '''Fix the voltage angle'''
97
+ self._t = theta
98
+ self._fixed_t = True
99
+
100
+ def unfixTheta(self):
101
+ '''Unfix the voltage angle'''
102
+ self._t = None
103
+ self._fixed_t = False
104
+
64
105
  @property
65
106
  def ID(self) -> str:
66
107
  '''Name of the bus'''
@@ -7,6 +7,7 @@ class ESSPolicy(Enum):
7
7
  Manual = "Manual" # Charging/discharging manually
8
8
  Time = "Time" # Charging/discharging at given period
9
9
  Price = "Price" # Charging at low price, discharging at high price
10
+ ByOptim = "Optim" # Charging according to solver optimization
10
11
 
11
12
  class ESSManualState(IntEnum):
12
13
  Idle = 0
@@ -51,8 +52,45 @@ class ESS:
51
52
  self._cprice = cprice
52
53
  self._dprice = dprice
53
54
  self._manstate = ESSManualState.Idle
55
+ self._manpower = 0.0
54
56
  self.P:FloatVar = None
55
57
 
58
+ def setManualPower(self, power: float):
59
+ '''
60
+ Set the manual power of the ESS
61
+ power: Power to charge/discharge, pu. Positive value means charging, negative value means discharging, 0.0 means idle.
62
+ '''
63
+ if power > 0:
64
+ self.setManualState(ESSManualState.Charge, power)
65
+ elif power < 0:
66
+ self.setManualState(ESSManualState.Discharge, -power)
67
+ else:
68
+ self.setManualState(ESSManualState.Idle, 0.0)
69
+
70
+ def setManualState(self, state: ESSManualState, power: Optional[float] = None):
71
+ '''
72
+ Set the manual state of the ESS
73
+ state: ESSManualState
74
+ power: Power to charge/discharge, pu, absolute value. If None, use MaxPc/MaxPd.
75
+ '''
76
+ self._manstate = state
77
+ if state == ESSManualState.Charge:
78
+ assert power is None or power >= 0, "Power must be >= 0 or None"
79
+ if power is None:
80
+ self._manpower = self.MaxPc
81
+ else:
82
+ self._manpower = power
83
+ elif state == ESSManualState.Discharge:
84
+ assert power is None or power >= 0, "Power must be >= 0 or None"
85
+ if power is None:
86
+ self._manpower = -self.MaxPd
87
+ else:
88
+ self._manpower = -power
89
+ else:
90
+ assert power == 0.0 or power is None, "Power must be 0 or None when state is Idle"
91
+ self._manpower = 0.0
92
+ self.P = self._manpower
93
+
56
94
  @property
57
95
  def Q(self) -> float:
58
96
  '''Reactive power output'''
@@ -63,18 +101,27 @@ class ESS:
63
101
  '''State of charge'''
64
102
  return self._elec / self._cap
65
103
 
66
- def Apply(self, dur_s:int):
104
+ def Apply(self, dur_second:int):
67
105
  if self.P is not None:
68
- dur = dur_s / 3600
106
+ dur = dur_second / 3600
69
107
  if self.P < 0:
70
108
  return self.Discharge(-self.P, dur)
71
109
  else:
72
110
  return self.Charge(self.P, dur)
73
111
  return 0
74
112
 
113
+ @property
114
+ def tanPhi(self) -> float:
115
+ '''tan φ = sqrt(1 - PF**2) / PF'''
116
+ return math.sqrt(1 - self._pf**2) / self._pf
117
+
75
118
  def __q(self, P: float) -> float:
76
119
  '''Calculate reactive power'''
77
- return P * math.sqrt(1 - self._pf**2)
120
+ return P * self.tanPhi
121
+
122
+ def P_var(self, bank: VarBank) -> Variable:
123
+ '''Return a variable for the power of the ESS. Positive value means charging, negative value means discharging.'''
124
+ return bank.fvar(f"{self.ID}_P", self, "P", value=self.P)
78
125
 
79
126
  def GetLoad(self, t: int, cprice:float, dprice:float) -> 'tuple[float, float]':
80
127
  '''
@@ -84,9 +131,9 @@ class ESS:
84
131
  '''
85
132
  if self._policy == ESSPolicy.Manual:
86
133
  if self._manstate == ESSManualState.Charge and self._elec < self._cap:
87
- return self._pc_max, self.__q(self._pc_max)
134
+ return self._manpower, self.__q(self._manpower)
88
135
  elif self._manstate == ESSManualState.Discharge and self._elec > 0:
89
- return -self._pd_max, -self.__q(self._pd_max)
136
+ return self._manpower, -self.__q(-self._manpower)
90
137
  elif self._policy == ESSPolicy.Time:
91
138
  if self._ctime is not None and t in self._ctime and self._elec < self._cap:
92
139
  return self._pc_max, self.__q(self._pc_max)
@@ -17,7 +17,7 @@ class Generator:
17
17
  pmin_pu: NFloatLike = None, pmax_pu: NFloatLike = None,
18
18
  qmin_pu: NFloatLike = None, qmax_pu: NFloatLike = None,
19
19
  Lat: NFloat = None, Lon: NFloat = None,
20
- P: NFloatLike = None, Q: NFloatLike = None,
20
+ P: NFloatLike = None, Q: NFloatLike = None, active: bool = True
21
21
  ):
22
22
  '''
23
23
  Initialize
@@ -71,6 +71,29 @@ class Generator:
71
71
  self.CostB = Float2Func(costB)
72
72
  self.CostC = Float2Func(costC)
73
73
  self.CostShadow = None
74
+ self.active = active
75
+
76
+ def P_var(self, bank: VarBank, t:int = 0) -> Variable:
77
+ '''Return a variable for the active power output'''
78
+ if self.FixedP:
79
+ raise ValueError("Active power output is fixed, cannot create a variable for it.")
80
+ pmin = self.Pmin(t) if isinstance(self.Pmin, TimeFunc) else self.Pmin
81
+ pmax = self.Pmax(t) if isinstance(self.Pmax, TimeFunc) else self.Pmax
82
+ p = self.P(t) if isinstance(self.P, TimeFunc) else self.P
83
+ return bank.fvar(f"{self.ID}_P", self, "_p", p, lb=pmin, ub=pmax)
84
+
85
+ def Q_var(self, bank: VarBank, t:int = 0) -> Variable:
86
+ if self.FixedQ:
87
+ raise ValueError("Reactive power output is fixed, cannot create a variable for it.")
88
+ qmin = self.Qmin(t) if isinstance(self.Qmin, TimeFunc) else self.Qmin
89
+ qmax = self.Qmax(t) if isinstance(self.Qmax, TimeFunc) else self.Qmax
90
+ q = self.Q(t) if isinstance(self.Q, TimeFunc) else self.Q
91
+ return bank.fvar(f"{self.ID}_Q", self, "_q", q, lb=qmin, ub=qmax)
92
+
93
+ def active_var(self, bank: VarBank) -> Variable:
94
+ if self.FixedP or self.FixedQ:
95
+ raise ValueError("Active or reactive power output is fixed, cannot create an active variable for it.")
96
+ return bank.bvar(f"{self.ID}_active", self, "active", True)
74
97
 
75
98
  @property
76
99
  def P(self) -> NFloatOrFunc:
@@ -84,6 +107,7 @@ class Generator:
84
107
 
85
108
  def fixP(self, p: float):
86
109
  '''Fix the active power output'''
110
+ self.active = True
87
111
  self._p = p
88
112
  self._fixed_p = True
89
113
 
@@ -104,6 +128,7 @@ class Generator:
104
128
 
105
129
  def fixQ(self, q: float):
106
130
  '''Fix the reactive power output'''
131
+ self.active = True
107
132
  self._q = q
108
133
  self._fixed_q = True
109
134
 
@@ -1,4 +1,5 @@
1
1
  from collections import deque
2
+ from itertools import chain
2
3
  from .grid import *
3
4
 
4
5
  class IslandResult(IntEnum):
@@ -88,4 +89,11 @@ class Island:
88
89
  Y[j, i] -= y
89
90
  Y[i, i] += y
90
91
  Y[j, j] += y
91
- return bus_dict, Y
92
+ return bus_dict, Y
93
+
94
+ def hasName(self, name: str) -> bool:
95
+ """Check if the island has a bus, generator, line, PVW or ESS with the given name."""
96
+ for s in chain(self.Buses, self.Gens, self.Lines, self.PVWs, self.ESSs):
97
+ if s in name:
98
+ return True
99
+ return False
@@ -31,6 +31,28 @@ class Line:
31
31
  self.L = length_km
32
32
  self.active = active
33
33
 
34
+ def active_var(self, bank: VarBank) -> Variable:
35
+ '''Return a variable indicating whether the line is active'''
36
+ return bank.bvar(f"{self.ID}_active", self, "active", value=self.active)
37
+
38
+ def I_var(self, bank: VarBank) -> Variable:
39
+ '''Return a variable for the current of the line'''
40
+ return bank.fvar(f"{self.ID}_I", self, "I", value=self.I, nonneg=True, lb=0.0, ub=self.max_I)
41
+
42
+ def I2_var(self, bank: VarBank) -> Variable:
43
+ '''Return a variable for the square of the current of the line'''
44
+ i = self.I if self.I is not None else 0.0
45
+ return bank.fvar(f"{self.ID}_I2", self, "I", value=i**2, nonneg=True,
46
+ lb=0.0, ub=self.max_I**2, reflect=lambda x: math.sqrt(x))
47
+
48
+ def P_var(self, bank: VarBank) -> Variable:
49
+ '''Return a variable for the real power flow of the line'''
50
+ return bank.fvar(f"{self.ID}_P", self, "P", value=self.P)
51
+
52
+ def Q_var(self, bank: VarBank) -> Variable:
53
+ '''Return a variable for the reactive power flow of the line'''
54
+ return bank.fvar(f"{self.ID}_Q", self, "Q", value=self.Q)
55
+
34
56
  @property
35
57
  def ID(self) -> str:
36
58
  '''Name of the line'''
@@ -53,15 +53,19 @@ class PVWind:
53
53
 
54
54
  @property
55
55
  def PF(self):
56
- '''Power factor, cos(phi). Reactive output Q = P * sqrt(1 - PF**2)'''
56
+ '''Power factor, cos(phi). Reactive output Q = P * tan φ'''
57
57
  return self._pf
58
58
  @PF.setter
59
59
  def PF(self, pf: float):
60
60
  self._pf = pf
61
61
 
62
+ @property
63
+ def tanPhi(self):
64
+ return math.sqrt(1 - self._pf**2) / self._pf
65
+
62
66
  def Q(self, _t):
63
67
  '''Reactive power output, pu'''
64
- return self.P(_t) * math.sqrt(1 - self._pf**2)
68
+ return self.P(_t) * self.tanPhi
65
69
 
66
70
  def position(self):
67
71
  '''Return the position of the PV Panel'''
@@ -103,6 +107,18 @@ class PVWind:
103
107
  '''Set the curtailment cost, $/puh'''
104
108
  self._cc = cc
105
109
 
110
+ def Pr_var(self, bank: VarBank, t:int = 0):
111
+ '''Return a variable for the real power output'''
112
+ return bank.fvar(f"{self.ID}_Pr", self, "_pr", value=self.P(t), nonneg=True, ub = self.P(t))
113
+
114
+ def Qr_var(self, bank: VarBank, t:int = 0):
115
+ '''Return a variable for the reactive power output'''
116
+ vp = self.Pr_var(bank, t)
117
+ vq = bank.fvar(f"{self.ID}_Qr", self, "_qr")
118
+ cons_name = f"{self.ID}_pf"
119
+ if cons_name not in bank._autocons:
120
+ bank._autocons[cons_name] = (vq == vp * self.tanPhi)
121
+
106
122
  @property
107
123
  def Pr(self):
108
124
  '''Real power output'''
@@ -61,7 +61,7 @@ class SolverBase(ABC):
61
61
  l.P = s.real
62
62
  l.Q = s.imag
63
63
 
64
- def solve(self, _t:int, /, **kwargs):
64
+ def solve(self, _t:int, /, calc_line:bool = True, **kwargs):
65
65
  ok_cnt = 0
66
66
  res_val = 0.0
67
67
  for i, il in enumerate(self._islands):
@@ -71,7 +71,7 @@ class SolverBase(ABC):
71
71
  if r == IslandResult.OK:
72
72
  ok_cnt += 1
73
73
  res_val += v
74
- self._calc_line_params()
74
+ if calc_line: self._calc_line_params()
75
75
  if ok_cnt == len(self._islands):
76
76
  return GridSolveResult.OK, res_val
77
77
  elif ok_cnt == 0:
@@ -19,13 +19,15 @@ class CombinedSolver(SolverBase):
19
19
  A class that use DistFlowSolver to estimate the power flow and then use OpenDSSSolver or NewtonSolver to solve the power flow problem.
20
20
  """
21
21
  def __init__(self, grid:Grid, eps:float = 1e-6, max_iter:int = 1000, *, mlrp:float = 0.5,
22
- default_saveto:str = DEFAULT_SAVETO, estimator:Estimator = Estimator.DistFlow,
22
+ default_saveto:str = DEFAULT_SAVETO, estimator:Union[Estimator, SolverBase] = Estimator.DistFlow,
23
23
  calculator:Calculator = Calculator.Newton, source_bus:'Union[str,Iterable[str]]' = ""):
24
24
  super().__init__(grid, eps, max_iter, default_saveto = default_saveto)
25
25
 
26
26
  from .soldist import DistFlowSolver
27
- assert estimator == Estimator.DistFlow, "Only DistFlow is supported for now."
28
- self.est = DistFlowSolver(grid, mlrp = mlrp)
27
+ if isinstance(estimator, Estimator):
28
+ assert estimator == Estimator.DistFlow, "Only DistFlow is supported for now."
29
+ estimator = DistFlowSolver(grid, mlrp = mlrp)
30
+ self.est = estimator
29
31
  self.cal_str = calculator
30
32
  if calculator in CALCULATORS_NEED_SOURCE_BUS:
31
33
  assert source_bus != "", "source_bus cannot be empty when using OpenDSSSolver."
@@ -0,0 +1,55 @@
1
+ from abc import abstractmethod
2
+ from typing import List, Optional, Tuple
3
+ import cvxpy as cp
4
+ from .island import Island, IslandResult
5
+ from .utils import VarBank
6
+ from .grid import Grid
7
+ from .solbase import DEFAULT_SAVETO, GridSolveResult, SolverBase
8
+
9
+ class ManualSolver(SolverBase):
10
+ """
11
+ A class that use DistFlowSolver to estimate the power flow and then use OpenDSSSolver or NewtonSolver to solve the power flow problem.
12
+ """
13
+ def __init__(self, grid:Grid, eps:float = 1e-6, max_iter:int = 1000, *,
14
+ default_saveto:str = DEFAULT_SAVETO, bank: Optional[VarBank] = None,
15
+ solver = cp.ECOS):
16
+ super().__init__(grid, eps, max_iter, default_saveto = default_saveto)
17
+ self.bank = bank if bank is not None else VarBank()
18
+ self.default_sovler = solver # Default solver, can be overridden in solve method
19
+
20
+ @abstractmethod
21
+ def proc_solution(self, i:int, _t:int, bank: VarBank, grid: Grid, island:Island) -> Tuple[List[cp.Constraint], cp.Expression]:
22
+ """
23
+ Process the solution for the island.
24
+ i: Index of the island in the grid
25
+ _t: Time step to solve
26
+ bank: Variable bank to store the variables and implict constraints
27
+ grid: The grid object
28
+ island: The island to solve
29
+ Returns a tuple of constraints and objective expression.
30
+ The objective will be minimized.
31
+ """
32
+ raise NotImplementedError
33
+
34
+ def solve(self, _t:int, /, *, timeout_s: float = 1, **kwargs) -> Tuple[GridSolveResult, float]:
35
+ ret = super().solve(_t, timeout_s=timeout_s, **kwargs)
36
+ self.bank.apply()
37
+ return ret
38
+
39
+ def solve_island(self, i:int, island:Island, _t:int, /, **kwargs) -> Tuple[IslandResult, float]:
40
+ """Solve the island"""
41
+ cons, obj = self.proc_solution(i, _t, self.bank, self._g, island)
42
+ for cname, c in self.bank._autocons.items():
43
+ if island.hasName(cname):
44
+ cons.append(c)
45
+
46
+ prob = cp.Problem(cp.Minimize(obj), cons)
47
+ try:
48
+ prob.solve(solver=self.default_sovler, verbose=False, max_iters=self.max_iter)
49
+ except cp.SolverError as e:
50
+ if "installed" in e.args[0]:
51
+ raise e
52
+ return IslandResult.Failed, -1
53
+ if prob.status not in (cp.OPTIMAL, cp.OPTIMAL_INACCURATE):
54
+ return IslandResult.Failed, -1
55
+ return IslandResult.OK, prob.value # type: ignore
@@ -178,7 +178,7 @@ class DistFlowSolver(SolverBase):
178
178
  # Add PVW constraints
179
179
  for pID, p in island.PVWItems():
180
180
  cons.append(pvwp[pID] <= p.P(_t))
181
- cons.append(pvwp[pID] * math.sqrt(1 - p.PF**2) == pvwq[pID])
181
+ cons.append(pvwp[pID] * p.tanPhi == pvwq[pID])
182
182
 
183
183
  # Bind GEN vars to Bus
184
184
  pg: 'dict[str, list[VF]]' = {b: [] for b in island.Buses}
@@ -274,8 +274,8 @@ class DistFlowSolver(SolverBase):
274
274
  cp.quad_over_lin(cp.hstack([P[lid], Q[lid]]), v[i]) <= l[lid]
275
275
  )
276
276
 
277
- for pID, p in island.PVWItems():
278
- cons.append(pvwp[pID] + cp.sqrt(1 - p.PF**2) == pvwq[pID])
277
+ #for pID, p in island.PVWItems():
278
+ # cons.append(pvwp[pID] + cp.sqrt(1 - p.PF**2) == pvwq[pID])
279
279
 
280
280
  # Objective components
281
281
  decs = self.C * (cp.sum(list(Pdec.values())) +
@@ -0,0 +1,90 @@
1
+ from typing import List, Optional, Tuple
2
+ import cvxpy as cp
3
+ from cvxpy import Constraint
4
+ from cvxpy import Expression
5
+ from .solbase import DEFAULT_SAVETO, GridSolveResult
6
+ from .grid import Grid
7
+ from .island import Island
8
+ from .utils import VarBank
9
+ from .solcvx import ManualSolver
10
+
11
+
12
+ class LinDistFlowSolver(ManualSolver):
13
+ def __init__(self, grid:Grid, eps:float = 1e-6, max_iter:int = 1000, *,
14
+ default_saveto:str = DEFAULT_SAVETO, bank: Optional[VarBank] = None,
15
+ solver = cp.ECOS_BB):
16
+ super().__init__(grid, eps, max_iter, default_saveto=default_saveto, bank=bank, solver=solver)
17
+
18
+ def solve(self, _t:int, /, *, timeout_s: float = 1) -> Tuple[GridSolveResult, float]:
19
+ return super().solve(_t, timeout_s=timeout_s, calc_line=False)
20
+
21
+ def proc_solution(self, i: int, _t:int, bank: VarBank, grid: Grid, island: Island) -> Tuple[List[Constraint], Expression]:
22
+ cons = []
23
+ obj = 0
24
+ # Bind GEN vars to Bus
25
+ pg: 'dict[str, list]' = {b: [] for b in island.Buses}
26
+ qg: 'dict[str, list]' = {b: [] for b in island.Buses}
27
+ pd: 'dict[str, float]' = {bID: b.Pd(_t) for bID, b in island.BusItems()}
28
+ qd: 'dict[str, float]' = {bID: b.Qd(_t) for bID, b in island.BusItems()}
29
+
30
+ # Collect power generation data and set objective
31
+ for gID, g in island.GenItems():
32
+ act = g.active_var(bank)
33
+ p = g.P_var(bank, _t)
34
+ q = g.Q_var(bank, _t)
35
+ pg[g.BusID].append(p)
36
+ qg[g.BusID].append(q)
37
+ obj += g.CostA(_t) * p ** 2 + g.CostB(_t) * p + g.CostC(_t)
38
+
39
+ # Collect power generation data for PV and ESS
40
+ for pID, p in island.PVWItems():
41
+ pg[p.BusID].append(p.Pr_var(bank, _t))
42
+ qg[p.BusID].append(p.Qr_var(bank, _t))
43
+
44
+ for eID, e in island.ESSItems():
45
+ p, q = e.GetLoad(_t, island.grid.ChargePrice(_t), island.grid.DischargePrice(_t))
46
+ e.P = p
47
+ if p > 0:
48
+ pd[e.BusID] += p
49
+ qd[e.BusID] += q
50
+ elif p < 0:
51
+ pg[e.BusID].append(-p)
52
+ qg[e.BusID].append(-q)
53
+
54
+ # Add power constraints for each bus
55
+ for j, bus in island.BusItems():
56
+ flow_in = island.grid.LinesOfTBus(j)
57
+ flow_out = island.grid.LinesOfFBus(j)
58
+
59
+ # P constraint
60
+ inflow = cp.sum([ln.P_var(bank) for ln in flow_in if ln.ID in island.Lines])
61
+ outflow = cp.sum([ln.P_var(bank) for ln in flow_out if ln.ID in island.Lines])
62
+ cons.append(
63
+ inflow + cp.sum(pg[j]) == outflow + pd[j]
64
+ )
65
+
66
+ # flow_in and flow_out are Python generators, which cannot be reused, thus needed to be re-assigned
67
+ flow_in = island.grid.LinesOfTBus(j)
68
+ flow_out = island.grid.LinesOfFBus(j)
69
+ # Q constraint
70
+ q_inflow = cp.sum([ln.Q_var(bank) for ln in flow_in if ln.ID in island.Lines])
71
+ q_outflow = cp.sum([ln.Q_var(bank) for ln in flow_out if ln.ID in island.Lines])
72
+ cons.append(
73
+ q_inflow + cp.sum(qg[j]) == q_outflow + qd[j]
74
+ )
75
+
76
+ # Add line constraints
77
+ for lid, l in island.LineItems():
78
+ fbus = grid.Bus(l.fBus)
79
+ tbus = grid.Bus(l.tBus)
80
+ if fbus is None or tbus is None:
81
+ raise ValueError(f"Line {l.ID} has no bus {l.fBus} or {l.tBus}")
82
+ act = l.active_var(bank)
83
+ vf = fbus.V2_var(bank) if not fbus.FixedV else fbus.V ** 2 # type: ignore
84
+ vt = tbus.V2_var(bank) if not tbus.FixedV else tbus.V ** 2 # type: ignore
85
+ p = l.P_var(bank)
86
+ q = l.Q_var(bank)
87
+ cons.append(vt == (vf - 2*l.R*p - 2*l.X*q))
88
+ l.I = None # Clear the current variable to avoid confusion
89
+
90
+ return cons, obj # type: ignore
@@ -1,4 +1,5 @@
1
- from typing import Optional, Union
1
+ from cvxpy import Variable, Constraint
2
+ from typing import Callable, Optional, Tuple, Union, List, Dict
2
3
  from feasytools import TimeFunc, SegFunc, ConstFunc
3
4
  from xml.etree.ElementTree import Element
4
5
 
@@ -10,6 +11,77 @@ NFloatLike = Union[None, FloatLike]
10
11
  FloatVals = Union[int, float]
11
12
 
12
13
 
14
+ class VarBank:
15
+ def __init__(self):
16
+ self._vars:Dict[str, Tuple[object, str, Variable, Optional[Callable]]] = {}
17
+ self._autocons:Dict[str, Constraint] = {}
18
+
19
+ def __var(self, name:str, obj: object, attr: str, value = None, boolean:bool = False, integer:bool = False,
20
+ nonneg:bool = False, lb: Optional[float] = None, ub: Optional[float] = None,
21
+ reflect:Optional[Callable] = None) -> Variable:
22
+ if name in self._vars:
23
+ return self._vars[name][2]
24
+ if hasattr(obj, attr):
25
+ value = getattr(obj, attr) if value is None else value
26
+ else:
27
+ raise ValueError(f"Object {obj} has no attribute {attr} to initialize variable {name}")
28
+ v = Variable(name = name, value = value, nonneg = nonneg, boolean = boolean, integer = integer)
29
+ self._vars[name] = (obj, attr, v, reflect)
30
+ if lb is not None and ((nonneg and lb > 0) or not nonneg):
31
+ if name + "_lb" not in self._autocons:
32
+ self._autocons[name + "_lb"] = (v >= lb)
33
+ if ub is not None and ub < float('inf'):
34
+ if nonneg and ub < 0:
35
+ raise ValueError(f"Upper bound {ub} is less than 0 for non-negative variable {name}")
36
+ if name + "_ub" not in self._autocons:
37
+ self._autocons[name + "_ub"] = (v <= ub)
38
+ return v
39
+ @property
40
+ def variables(self) -> Dict[str, Variable]:
41
+ '''Get all variables in the bank.'''
42
+ return {name: var[2] for name, var in self._vars.items()}
43
+
44
+ @property
45
+ def constraints(self) -> Dict[str, Constraint]:
46
+ '''Get all constraints in the bank.'''
47
+ return self._autocons
48
+
49
+ def __getitem__(self, name: str) -> Variable:
50
+ '''Get a variable by name.'''
51
+ if name in self._vars:
52
+ return self._vars[name][2]
53
+ else:
54
+ raise KeyError(f"Variable {name} not found in the bank.")
55
+
56
+ def fvar(self, name:str, obj: object, attr: str, value:Optional[float] = None,
57
+ nonneg:bool = False, lb: Optional[float] = None, ub: Optional[float] = None,
58
+ reflect:Optional[Callable[[float], float]] = None) -> Variable:
59
+ '''Create a variable with the given name and attributes.'''
60
+ return self.__var(name, obj, attr, value, False, False, nonneg, lb, ub, reflect)
61
+
62
+ def ivar(self, name:str, obj: object, attr: str, value:Optional[int] = None,
63
+ nonneg:bool = False, lb: Optional[float] = None, ub: Optional[float] = None,
64
+ reflect:Optional[Callable[[int], int]] = None) -> Variable:
65
+ '''Create an integer variable with the given name and attributes.'''
66
+ return self.__var(name, obj, attr, value, False, True, nonneg, lb, ub, reflect)
67
+
68
+ def bvar(self, name:str, obj: object, attr: str, value:Optional[bool] = None):
69
+ '''Create a boolean variable with the given name and attributes.'''
70
+ return self.__var(name, obj, attr, value, True, False, False, None, None)
71
+
72
+ def apply(self):
73
+ for obj, attr, v, ref in self._vars.values():
74
+ if hasattr(obj, attr):
75
+ if v.value is None:
76
+ setattr(obj, attr, None)
77
+ else:
78
+ setattr(obj, attr, v.value if ref is None else ref(v.value))
79
+ else:
80
+ raise AttributeError(f"Object {obj} has no attribute {attr}")
81
+
82
+ def __contains__(self, name: str) -> bool:
83
+ return name in self._vars
84
+
13
85
  def Float2Func(v: FloatLike) -> TimeFunc:
14
86
  if isinstance(v, (float, int)):
15
87
  return ConstFunc(v)
@@ -1,6 +1,6 @@
1
- Metadata-Version: 2.2
1
+ Metadata-Version: 2.4
2
2
  Name: fpowerkit
3
- Version: 0.3.1
3
+ Version: 0.3.3rc0
4
4
  Summary: A PDN solver with multiple solutions.
5
5
  Author: fmy_xfk
6
6
  Classifier: Programming Language :: Python :: 3
@@ -15,6 +15,7 @@ Dynamic: author
15
15
  Dynamic: classifier
16
16
  Dynamic: description
17
17
  Dynamic: description-content-type
18
+ Dynamic: license-file
18
19
  Dynamic: requires-dist
19
20
  Dynamic: requires-python
20
21
  Dynamic: summary
@@ -31,10 +32,11 @@ This package is affiliated to V2Sim, an open-aource microscopic V2G simulation p
31
32
  journal={IEEE Transactions on Smart Grid},
32
33
  title={V2Sim: An Open-Source Microscopic V2G Simulation Platform in Urban Power and Transportation Network},
33
34
  year={2025},
34
- pages={1-1},
35
- 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},
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},
36
39
  doi={10.1109/TSG.2025.3560976}}
37
-
38
40
  ```
39
41
 
40
42
  There are 3 modes for this package to work:
@@ -12,8 +12,10 @@ fpowerkit/line.py
12
12
  fpowerkit/pvwind.py
13
13
  fpowerkit/solbase.py
14
14
  fpowerkit/solcmb.py
15
+ fpowerkit/solcvx.py
15
16
  fpowerkit/soldist.py
16
17
  fpowerkit/soldss.py
18
+ fpowerkit/solldf.py
17
19
  fpowerkit/solnt.py
18
20
  fpowerkit/utils.py
19
21
  fpowerkit.egg-info/PKG-INFO
@@ -5,7 +5,7 @@ with open("desc.md", "r", encoding="utf8") as f:
5
5
 
6
6
  setup(
7
7
  name="fpowerkit",
8
- version="0.3.1",
8
+ version="0.3.3rc0",
9
9
  author="fmy_xfk",
10
10
  packages=find_packages(),
11
11
  description="A PDN solver with multiple solutions.",
File without changes
File without changes