fpowerkit 0.3.3rc0__tar.gz → 0.3.5__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 (38) hide show
  1. fpowerkit-0.3.5/.gitignore +9 -0
  2. fpowerkit-0.3.5/PKG-INFO +89 -0
  3. {fpowerkit-0.3.3rc0 → fpowerkit-0.3.5}/README.md +13 -0
  4. fpowerkit-0.3.5/desc.md +58 -0
  5. fpowerkit-0.3.5/fpowerkit/__init__.py +17 -0
  6. {fpowerkit-0.3.3rc0 → fpowerkit-0.3.5}/fpowerkit/bus.py +6 -1
  7. {fpowerkit-0.3.3rc0 → fpowerkit-0.3.5}/fpowerkit/cases.py +3 -1
  8. {fpowerkit-0.3.3rc0 → fpowerkit-0.3.5}/fpowerkit/ess.py +7 -3
  9. {fpowerkit-0.3.3rc0 → fpowerkit-0.3.5}/fpowerkit/gen.py +9 -4
  10. {fpowerkit-0.3.3rc0 → fpowerkit-0.3.5}/fpowerkit/grid.py +10 -8
  11. {fpowerkit-0.3.3rc0 → fpowerkit-0.3.5}/fpowerkit/island.py +6 -3
  12. {fpowerkit-0.3.3rc0 → fpowerkit-0.3.5}/fpowerkit/line.py +11 -7
  13. fpowerkit-0.3.5/fpowerkit/lpwrapper.py +286 -0
  14. {fpowerkit-0.3.3rc0 → fpowerkit-0.3.5}/fpowerkit/pvwind.py +4 -1
  15. {fpowerkit-0.3.3rc0 → fpowerkit-0.3.5}/fpowerkit/solbase.py +5 -2
  16. {fpowerkit-0.3.3rc0 → fpowerkit-0.3.5}/fpowerkit/solcmb.py +5 -3
  17. {fpowerkit-0.3.3rc0 → fpowerkit-0.3.5}/fpowerkit/solcvx.py +13 -7
  18. {fpowerkit-0.3.3rc0 → fpowerkit-0.3.5}/fpowerkit/soldist.py +10 -6
  19. {fpowerkit-0.3.3rc0 → fpowerkit-0.3.5}/fpowerkit/soldss.py +8 -2
  20. fpowerkit-0.3.5/fpowerkit/solldf.py +156 -0
  21. fpowerkit-0.3.5/fpowerkit/solldf2.py +144 -0
  22. {fpowerkit-0.3.3rc0 → fpowerkit-0.3.5}/fpowerkit/solnt.py +14 -4
  23. {fpowerkit-0.3.3rc0 → fpowerkit-0.3.5}/fpowerkit/utils.py +31 -8
  24. fpowerkit-0.3.5/main.py +117 -0
  25. fpowerkit-0.3.5/pyproject.toml +55 -0
  26. fpowerkit-0.3.5/test.py +127 -0
  27. fpowerkit-0.3.5/test314t.py +37 -0
  28. fpowerkit-0.3.3rc0/PKG-INFO +0 -52
  29. fpowerkit-0.3.3rc0/fpowerkit/__init__.py +0 -8
  30. fpowerkit-0.3.3rc0/fpowerkit/solldf.py +0 -90
  31. fpowerkit-0.3.3rc0/fpowerkit.egg-info/PKG-INFO +0 -52
  32. fpowerkit-0.3.3rc0/fpowerkit.egg-info/SOURCES.txt +0 -25
  33. fpowerkit-0.3.3rc0/fpowerkit.egg-info/dependency_links.txt +0 -1
  34. fpowerkit-0.3.3rc0/fpowerkit.egg-info/requires.txt +0 -2
  35. fpowerkit-0.3.3rc0/fpowerkit.egg-info/top_level.txt +0 -1
  36. fpowerkit-0.3.3rc0/setup.cfg +0 -4
  37. fpowerkit-0.3.3rc0/setup.py +0 -21
  38. {fpowerkit-0.3.3rc0 → fpowerkit-0.3.5}/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
@@ -0,0 +1,89 @@
1
+ Metadata-Version: 2.4
2
+ Name: fpowerkit
3
+ Version: 0.3.5
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: ldf
26
+ Requires-Dist: numpy>=1.19.0; extra == 'ldf'
27
+ Requires-Dist: scipy; extra == 'ldf'
28
+ Provides-Extra: newton
29
+ Requires-Dist: numpy>=1.19.0; extra == 'newton'
30
+ Description-Content-Type: text/markdown
31
+
32
+ # FPowerKit - A power distribution network calculation component
33
+
34
+ This is a package designed for power distribution network description and solving.
35
+
36
+ This package is affiliated to V2Sim, an open-aource microscopic V2G simulation platform in urban power and transportation network. If you are using the modified DistFlow model in this package, please cite the [paper](https://ieeexplore.ieee.org/document/10970754):
37
+
38
+ ```
39
+ @ARTICLE{10970754,
40
+ author={Qian, Tao and Fang, Mingyu and Hu, Qinran and Shao, Chengcheng and Zheng, Junyi},
41
+ journal={IEEE Transactions on Smart Grid},
42
+ title={V2Sim: An Open-Source Microscopic V2G Simulation Platform in Urban Power and Transportation Network},
43
+ year={2025},
44
+ volume={16},
45
+ number={4},
46
+ pages={3167-3178},
47
+ 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},
48
+ doi={10.1109/TSG.2025.3560976}}
49
+ ```
50
+
51
+ ### Solvers available
52
+ There are multiple solvers can be used in FPowerKit.
53
+ - **Power flow calculation**
54
+ - **Newton-Raphson**: Classical method for power flow calculation. **(GIL-free Compatible)**
55
+ - **OpenDSS**: Call external OpenDSS for distribution network solving.
56
+ - **Optimal power flow (OPF)**
57
+ - **DistFlow**: A classical OPF model for radial distribution network, with both quadratic and linear objective of minimal active generation cost.
58
+ - **LinDistFlow**: A typical simplification of DistFlow.
59
+ - **LinDistFlow2**: A **GIL-free compatible** version of LinDistFlow, only supporting linear objective.
60
+
61
+
62
+ There are also some abstract solvers for users to customize:
63
+ - **Combined Solver**: Combine two solvers to accomplish both OPF and accuracte power flow calculation. For example, use LinDistFlow + OpenDSS to get the optimal generation and the accurate power flow. The only GIL-free compatible combination is LinDistFlow2 + Newton.
64
+ - **Manual Solver**: Allow user to customize constraints
65
+
66
+ ### Installation options
67
+ If you want to use different features, install with different command:
68
+
69
+ |Feature|Command|
70
+ |---|---|
71
+ |Only grid description|`pip install fpowerkit`|
72
+ |Y matrix & Newton|`pip install fpowerkit[newton]`|
73
+ |OpenDSS|`pip install fpowerkit[dss]`|
74
+ |DistFlow|`pip install fpowerkit[distflow]`|
75
+ |LinDistFlow|`pip install fpowerkit[ldf]`|
76
+ |All|`pip install fpowerkit[full]`|
77
+
78
+ Secondary development on this package requires all features.
79
+
80
+ ### Introduction
81
+ There are 3 modes for this package to work:
82
+
83
+ - Optimal power flow (OPF): Use cvxpy to solve the optimal power flow and determine the output of the generators.
84
+
85
+ - Power flow calculation: Use OpenDSS/Newton-Raphson method to solve the power flow.
86
+
87
+ - Hybrid: Use OPF to determine the initial value, and then use OpenDSS/Newton-Raphson to perform accurate calculation.
88
+
89
+ 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))
@@ -0,0 +1,58 @@
1
+ # FPowerKit - A power distribution network calculation component
2
+
3
+ This is a package designed for power distribution network description and solving.
4
+
5
+ This package is affiliated to V2Sim, an open-aource microscopic V2G simulation platform in urban power and transportation network. If you are using the modified DistFlow model in this package, please cite the [paper](https://ieeexplore.ieee.org/document/10970754):
6
+
7
+ ```
8
+ @ARTICLE{10970754,
9
+ author={Qian, Tao and Fang, Mingyu and Hu, Qinran and Shao, Chengcheng and Zheng, Junyi},
10
+ journal={IEEE Transactions on Smart Grid},
11
+ title={V2Sim: An Open-Source Microscopic V2G Simulation Platform in Urban Power and Transportation Network},
12
+ year={2025},
13
+ volume={16},
14
+ number={4},
15
+ pages={3167-3178},
16
+ 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},
17
+ doi={10.1109/TSG.2025.3560976}}
18
+ ```
19
+
20
+ ### Solvers available
21
+ There are multiple solvers can be used in FPowerKit.
22
+ - **Power flow calculation**
23
+ - **Newton-Raphson**: Classical method for power flow calculation. **(GIL-free Compatible)**
24
+ - **OpenDSS**: Call external OpenDSS for distribution network solving.
25
+ - **Optimal power flow (OPF)**
26
+ - **DistFlow**: A classical OPF model for radial distribution network, with both quadratic and linear objective of minimal active generation cost.
27
+ - **LinDistFlow**: A typical simplification of DistFlow.
28
+ - **LinDistFlow2**: A **GIL-free compatible** version of LinDistFlow, only supporting linear objective.
29
+
30
+
31
+ There are also some abstract solvers for users to customize:
32
+ - **Combined Solver**: Combine two solvers to accomplish both OPF and accuracte power flow calculation. For example, use LinDistFlow + OpenDSS to get the optimal generation and the accurate power flow. The only GIL-free compatible combination is LinDistFlow2 + Newton.
33
+ - **Manual Solver**: Allow user to customize constraints
34
+
35
+ ### Installation options
36
+ If you want to use different features, install with different command:
37
+
38
+ |Feature|Command|
39
+ |---|---|
40
+ |Only grid description|`pip install fpowerkit`|
41
+ |Y matrix & Newton|`pip install fpowerkit[newton]`|
42
+ |OpenDSS|`pip install fpowerkit[dss]`|
43
+ |DistFlow|`pip install fpowerkit[distflow]`|
44
+ |LinDistFlow|`pip install fpowerkit[ldf]`|
45
+ |All|`pip install fpowerkit[full]`|
46
+
47
+ Secondary development on this package requires all features.
48
+
49
+ ### Introduction
50
+ There are 3 modes for this package to work:
51
+
52
+ - Optimal power flow (OPF): Use cvxpy to solve the optimal power flow and determine the output of the generators.
53
+
54
+ - Power flow calculation: Use OpenDSS/Newton-Raphson method to solve the power flow.
55
+
56
+ - Hybrid: Use OPF to determine the initial value, and then use OpenDSS/Newton-Raphson to perform accurate calculation.
57
+
58
+ Please visit https://gitee.com/fmy_xfk/fpowerkit to read the detailed introduction and the usage.
@@ -0,0 +1,17 @@
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 .solldf2 import *
16
+ from .solnt import *
17
+ 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']
@@ -0,0 +1,286 @@
1
+ from copy import deepcopy
2
+ from dataclasses import dataclass
3
+ from typing import Dict, Iterable, List, Optional, Union
4
+
5
+
6
+ @dataclass
7
+ class _LPVar:
8
+ name:str
9
+ idx:int
10
+ lb:Optional[float] = 0
11
+ ub:Optional[float] = None
12
+ x:Optional[float] = None # Solution value
13
+
14
+ def __add__(self, other):
15
+ expr = _LPExpr()
16
+ expr.add_term(self.idx, 1.0)
17
+ if isinstance(other, _LPExpr):
18
+ return expr + other
19
+ elif isinstance(other, _LPVar):
20
+ expr.add_term(other.idx, 1.0)
21
+ return expr
22
+ elif isinstance(other, (int, float)):
23
+ expr.add_const(other)
24
+ return expr
25
+ else:
26
+ raise TypeError("Unsupported type for addition")
27
+
28
+ def __sub__(self, other):
29
+ expr = _LPExpr()
30
+ expr.add_term(self.idx, 1.0)
31
+ if isinstance(other, _LPExpr):
32
+ return expr - other
33
+ elif isinstance(other, _LPVar):
34
+ expr.add_term(other.idx, -1.0)
35
+ return expr
36
+ elif isinstance(other, (int, float)):
37
+ expr.add_const(-other)
38
+ return expr
39
+ else:
40
+ raise TypeError("Unsupported type for subtraction")
41
+
42
+ def __neg__(self):
43
+ expr = _LPExpr()
44
+ expr.add_term(self.idx, -1.0)
45
+ return expr
46
+
47
+ def __mul__(self, scalar:Union[float, int]):
48
+ expr = _LPExpr()
49
+ expr.add_term(self.idx, scalar)
50
+ return expr
51
+
52
+ def __rmul__(self, scalar:Union[float, int]):
53
+ return self.__mul__(scalar)
54
+
55
+ def __div__(self, scalar:Union[float, int]):
56
+ expr = _LPExpr()
57
+ expr.add_term(self.idx, 1.0 / scalar)
58
+ return expr
59
+
60
+ class _LPEqCons: # expr == 0
61
+ def __init__(self, expr:'_LPExpr'):
62
+ self.expr = expr
63
+ self.rhs = -self.expr.const
64
+ self.expr.const = 0
65
+
66
+ class _LPIneqCons: # expr <= 0
67
+ def __init__(self, expr:'_LPExpr'):
68
+ self.expr = expr
69
+ self.rhs = -self.expr.const
70
+ self.expr.const = 0
71
+
72
+ class _LPExpr:
73
+ def __init__(self):
74
+ self.terms:Dict[int, float] = {} # var_idx -> coefficient
75
+ self.const = 0.0
76
+
77
+ def add_term(self, var_idx:int, coeff:float):
78
+ if var_idx in self.terms:
79
+ self.terms[var_idx] += coeff
80
+ else:
81
+ self.terms[var_idx] = coeff
82
+
83
+ def add_const(self, value:float):
84
+ self.const += value
85
+
86
+ def __add__(self, other):
87
+ result = deepcopy(self)
88
+
89
+ if isinstance(other, _LPExpr):
90
+ for var_idx, coeff in other.terms.items():
91
+ result.add_term(var_idx, coeff)
92
+ result.add_const(other.const)
93
+ elif isinstance(other, _LPVar):
94
+ result.add_term(other.idx, 1.0)
95
+ elif isinstance(other, (int, float)):
96
+ result.add_const(other)
97
+ else:
98
+ raise TypeError("Unsupported type for addition")
99
+ return result
100
+
101
+ def __radd__(self, other):
102
+ return self.__add__(other)
103
+
104
+ def __sub__(self, other):
105
+ result = deepcopy(self)
106
+
107
+ if isinstance(other, _LPExpr):
108
+ for var_idx, coeff in other.terms.items():
109
+ result.add_term(var_idx, -coeff)
110
+ result.add_const(-other.const)
111
+ elif isinstance(other, _LPVar):
112
+ result.add_term(other.idx, -1.0)
113
+ elif isinstance(other, (int, float)):
114
+ result.add_const(-other)
115
+ else:
116
+ raise TypeError("Unsupported type for subtraction")
117
+ return result
118
+
119
+ def __rsub__(self, other):
120
+ if isinstance(other, _LPExpr):
121
+ return other - self
122
+ elif isinstance(other, _LPVar):
123
+ result = _LPExpr()
124
+ result.add_term(other.idx, 1.0)
125
+ elif isinstance(other, (int, float)):
126
+ result = _LPExpr()
127
+ result.add_const(other)
128
+ else:
129
+ raise TypeError("Unsupported type for subtraction")
130
+
131
+ return result - self
132
+
133
+ def __neg__(self):
134
+ result = deepcopy(self)
135
+ for var_idx in result.terms:
136
+ result.terms[var_idx] = -result.terms[var_idx]
137
+ result.const = -result.const
138
+ return result
139
+
140
+ def __mul__(self, scalar:Union[float, int]):
141
+ result = deepcopy(self)
142
+ for var_idx in result.terms:
143
+ result.terms[var_idx] *= scalar
144
+ result.const *= scalar
145
+ return result
146
+
147
+ def __rmul__(self, scalar:Union[float, int]):
148
+ return self.__mul__(scalar)
149
+
150
+ def __div__(self, scalar:Union[float, int]):
151
+ result = deepcopy(self)
152
+ for var_idx in result.terms:
153
+ result.terms[var_idx] /= scalar
154
+ result.const /= scalar
155
+ return result
156
+
157
+ def __eq__(self, other):
158
+ return _LPEqCons(self - other)
159
+
160
+ def __le__(self, other):
161
+ return _LPIneqCons(self - other)
162
+
163
+ def __ge__(self, other):
164
+ return _LPIneqCons(other - self)
165
+
166
+ def quicksum(items:Iterable[Union[_LPVar, _LPExpr]]) -> _LPExpr:
167
+ result = _LPExpr()
168
+ for other in items:
169
+ if isinstance(other, _LPExpr):
170
+ for var_idx, coeff in other.terms.items():
171
+ result.add_term(var_idx, coeff)
172
+ result.add_const(other.const)
173
+ elif isinstance(other, _LPVar):
174
+ result.add_term(other.idx, 1.0)
175
+ elif isinstance(other, (int, float)):
176
+ result.add_const(other)
177
+ else:
178
+ raise TypeError("Unsupported type for addition")
179
+ return result
180
+
181
+ class LinProgProblem:
182
+ def __init__(self):
183
+ self.__vars:List[_LPVar] = []
184
+ self.__eqs:List[_LPEqCons] = []
185
+ self.__ineqs:List[_LPIneqCons] = []
186
+ self.objective:_LPExpr = _LPExpr()
187
+
188
+ def add_var(self, name:str, lb:Optional[float] = 0, ub: Optional[float] = None):
189
+ """
190
+ Add a variable to the linear programming problem.
191
+ name: Name of the variable
192
+ lb: Lower bound of the variable
193
+ ub: Upper bound of the variable
194
+ """
195
+ idx = len(self.__vars)
196
+ v = _LPVar(name, idx, lb, ub)
197
+ self.__vars.append(v)
198
+ return v
199
+
200
+ def add_cons(self, cons:Union[_LPEqCons, _LPIneqCons, bool]):
201
+ """
202
+ Add a constraint to the linear programming problem.
203
+ cons: The constraint to add (either equality or inequality)
204
+ """
205
+ if isinstance(cons, _LPEqCons):
206
+ self.__eqs.append(cons)
207
+ elif isinstance(cons, _LPIneqCons):
208
+ self.__ineqs.append(cons)
209
+ elif isinstance(cons, bool):
210
+ if not cons:
211
+ raise ValueError("Infeasible constraint (False) added to the problem")
212
+ else:
213
+ raise TypeError("Unsupported constraint type")
214
+
215
+ def set_objective(self, expr:Union[int, float, _LPExpr]):
216
+ """
217
+ Set the objective function for the linear programming problem.
218
+ """
219
+ if isinstance(expr, (int, float)):
220
+ expr_obj = _LPExpr()
221
+ expr_obj.add_const(expr)
222
+ self.objective = expr_obj
223
+ else:
224
+ self.objective = expr
225
+
226
+ def solve(self, minimize:bool = True):
227
+ """
228
+ Solve the linear programming problem.
229
+ minimize: If True, minimize the objective; if False, maximize it.
230
+ Returns: (status_code:int, objective_value:float)
231
+ status_code: 0 if successful, non-zero otherwise.
232
+ objective_value: The optimal objective value if successful, 0.0 otherwise.
233
+ """
234
+ obj = self.objective
235
+ if not minimize:
236
+ obj = -obj
237
+ try:
238
+ from scipy.optimize import linprog
239
+ import numpy as np
240
+ except Exception as e:
241
+ raise RuntimeError("scipy.optimize.linprog is required") from e
242
+
243
+ # objective coefficients
244
+ n = len(self.__vars)
245
+ c = np.zeros(n)
246
+ for var_idx, coeff in obj.terms.items():
247
+ c[var_idx] = coeff
248
+
249
+ # variable bounds (None means unbounded for linprog)
250
+ bounds = [(v.lb, v.ub) for v in self.__vars]
251
+
252
+ # equality constraints
253
+ m1 = len(self.__eqs)
254
+ if m1 > 0:
255
+ A_eq = np.zeros((m1, n))
256
+ b_eq = np.zeros(m1)
257
+ for i, eq in enumerate(self.__eqs):
258
+ for var_idx, coeff in eq.expr.terms.items():
259
+ A_eq[i, var_idx] = coeff
260
+ b_eq[i] = eq.rhs
261
+ else:
262
+ A_eq = None
263
+ b_eq = None
264
+
265
+ # inequality constraints (A_ub x <= b_ub)
266
+ m2 = len(self.__ineqs)
267
+ if m2 > 0:
268
+ A_ub = np.zeros((m2, n))
269
+ b_ub = np.zeros(m2)
270
+ for i, ineq in enumerate(self.__ineqs):
271
+ for var_idx, coeff in ineq.expr.terms.items():
272
+ A_ub[i, var_idx] = coeff
273
+ b_ub[i] = ineq.rhs
274
+ else:
275
+ A_ub = None
276
+ b_ub = None
277
+
278
+ res = linprog(c=c, A_ub=A_ub, b_ub=b_ub, A_eq=A_eq, b_eq=b_eq, bounds=bounds, method='highs')
279
+
280
+ if not res.success:
281
+ return res.status, 0.0
282
+
283
+ for i, v in enumerate(self.__vars):
284
+ v.x = res.x[i]
285
+
286
+ return res.status, float(res.fun) + obj.const