mipx 0.2.16__py2.py3-none-any.whl

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.

Potentially problematic release.


This version of mipx might be problematic. Click here for more details.

Files changed (47) hide show
  1. mipx/__init__.py +16 -0
  2. mipx/__pycache__/__init__.cpython-310.pyc +0 -0
  3. mipx/__pycache__/__init__.cpython-311.pyc +0 -0
  4. mipx/__pycache__/_version.cpython-310.pyc +0 -0
  5. mipx/__pycache__/constants.cpython-310.pyc +0 -0
  6. mipx/__pycache__/constants.cpython-311.pyc +0 -0
  7. mipx/__pycache__/cplexcpsolver.cpython-310.pyc +0 -0
  8. mipx/__pycache__/cplexcpsolver.cpython-311.pyc +0 -0
  9. mipx/__pycache__/cplexmpsolver.cpython-310.pyc +0 -0
  10. mipx/__pycache__/cplexmpsolver.cpython-311.pyc +0 -0
  11. mipx/__pycache__/cplexsolver.cpython-310.pyc +0 -0
  12. mipx/__pycache__/cpsolver.cpython-310.pyc +0 -0
  13. mipx/__pycache__/cpsolver.cpython-311.pyc +0 -0
  14. mipx/__pycache__/func.cpython-310.pyc +0 -0
  15. mipx/__pycache__/interface_.cpython-310.pyc +0 -0
  16. mipx/__pycache__/interface_.cpython-311.pyc +0 -0
  17. mipx/__pycache__/lineExpr.cpython-310.pyc +0 -0
  18. mipx/__pycache__/lineExpr.cpython-311.pyc +0 -0
  19. mipx/__pycache__/solver.cpython-310.pyc +0 -0
  20. mipx/__pycache__/solver.cpython-311.pyc +0 -0
  21. mipx/__pycache__/tupledict.cpython-310.pyc +0 -0
  22. mipx/__pycache__/tupledict.cpython-311.pyc +0 -0
  23. mipx/__pycache__/tuplelist.cpython-310.pyc +0 -0
  24. mipx/__pycache__/tuplelist.cpython-311.pyc +0 -0
  25. mipx/__pycache__/utilx.cpython-310.pyc +0 -0
  26. mipx/__pycache__/utilx.cpython-311.pyc +0 -0
  27. mipx/__pycache__/variable.cpython-310.pyc +0 -0
  28. mipx/__pycache__/variable.cpython-311.pyc +0 -0
  29. mipx/__version__.py +13 -0
  30. mipx/_version.py +13 -0
  31. mipx/constants.py +82 -0
  32. mipx/cplexcpsolver.py +300 -0
  33. mipx/cplexmpsolver.py +327 -0
  34. mipx/cpsolver.py +350 -0
  35. mipx/func.py +46 -0
  36. mipx/interface_.py +516 -0
  37. mipx/lineExpr.py +118 -0
  38. mipx/solver.py +873 -0
  39. mipx/tupledict.py +145 -0
  40. mipx/tuplelist.py +175 -0
  41. mipx/utilx.py +135 -0
  42. mipx/variable.py +187 -0
  43. mipx-0.2.16.dist-info/LICENSE +202 -0
  44. mipx-0.2.16.dist-info/METADATA +15 -0
  45. mipx-0.2.16.dist-info/RECORD +47 -0
  46. mipx-0.2.16.dist-info/WHEEL +6 -0
  47. mipx-0.2.16.dist-info/top_level.txt +1 -0
mipx/__init__.py ADDED
@@ -0,0 +1,16 @@
1
+ # -*- coding: utf-8 -*-
2
+ # @Time : 2023/3/31 22:18
3
+ # @Author : luyi
4
+ from .constants import *
5
+ from .lineExpr import LineExpr
6
+ from .solver import Model
7
+ from .tupledict import tupledict, multidict
8
+ from .tuplelist import tuplelist
9
+ from .utilx import name_str
10
+ from .func import debugVar
11
+ from .variable import Var, IntervalVar
12
+ from ._version import __version__
13
+ BINARY, CONTINUOUS, INTEGER = Vtype
14
+ MINIMIZE, MAXIMIZE = ObjType
15
+ LESS_EQUAL, EQUAL, GREATER_EQUAL = CmpType
16
+ name = 'mipx'
Binary file
Binary file
Binary file
Binary file
Binary file
mipx/__version__.py ADDED
@@ -0,0 +1,13 @@
1
+ # .__
2
+ # _____ |__|________ ___
3
+ # / \| \____ \ \/ /
4
+ # | Y Y \ | |_> > <
5
+ # |__|_| /__| __/__/\_ \
6
+ # \/ |__| \/
7
+ __title__ = "mipx"
8
+ __description__ = "mipx"
9
+ __version__ = "0.1.1"
10
+ __author__ = "luyi"
11
+ __author_email__ = "yi.lu@cisdi.com.cn"
12
+
13
+ __copyright__ = "Copyright CISDI"
mipx/_version.py ADDED
@@ -0,0 +1,13 @@
1
+ # .__
2
+ # _____ |__|________ ___
3
+ # / \| \____ \ \/ /
4
+ # | Y Y \ | |_> > <
5
+ # |__|_| /__| __/__/\_ \
6
+ # \/ |__| \/
7
+ __title__ = "mipx"
8
+ __description__ = "mipx"
9
+ __version__ = "0.2.16"
10
+ __author__ = "luyi"
11
+ __author_email__ = "yi.lu@cisdi.com.cn"
12
+
13
+ __copyright__ = "Copyright CISDI"
mipx/constants.py ADDED
@@ -0,0 +1,82 @@
1
+ # -*- coding: utf-8 -*-
2
+ # @Time : 2023/3/31 22:21
3
+ # @Author : luyi
4
+ from enum import Enum
5
+ from typing import Literal, Optional
6
+
7
+
8
+ P1, P2, P3, P4, P5, P6, P7, P8, P9 = 1, 10, 100, 1000, 10000, 100000, 1000000, 10000000, 100000000
9
+
10
+
11
+ class Vtype(Enum):
12
+ BINARY = "B"
13
+ CONTINUOUS = "C"
14
+ INTEGER = "I"
15
+
16
+
17
+ class ObjType(Enum):
18
+ MINIMIZE = "MIN"
19
+ MAXIMIZE = "MAX"
20
+
21
+
22
+ # optimization status
23
+ class OptimizationStatus(Enum):
24
+ """Status of the optimization"""
25
+
26
+ ERROR = -1
27
+ """Solver returned an error"""
28
+
29
+ OPTIMAL = 0
30
+ """Optimal solution was computed"""
31
+
32
+ INFEASIBLE = 1
33
+ """The model is proven infeasible"""
34
+
35
+ UNBOUNDED = 2
36
+ """One or more variables that appear in the objective function are not
37
+ included in binding constraints and the optimal objective value is
38
+ infinity."""
39
+
40
+ FEASIBLE = 3
41
+ """An integer feasible solution was found during the search but the search
42
+ was interrupted before concluding if this is the optimal solution or
43
+ not."""
44
+
45
+ INT_INFEASIBLE = 4
46
+ """A feasible solution exist for the relaxed linear program but not for the
47
+ problem with existing integer variables"""
48
+
49
+ NO_SOLUTION_FOUND = 5
50
+ """A truncated search was executed and no integer feasible solution was
51
+ found"""
52
+
53
+ LOADED = 6
54
+ """The problem was loaded but no optimization was performed"""
55
+
56
+ CUTOFF = 7
57
+ """No feasible solution exists for the current cutoff"""
58
+
59
+ OTHER = 10000
60
+
61
+
62
+ class CmpType(Enum):
63
+ LESS_EQUAL = 0
64
+ EQUAL = 1
65
+ GREATER_EQUAL = 2
66
+
67
+
68
+ class Params:
69
+ def __init__(self):
70
+ self.TimeLimit: Optional[int] = None # 单位秒
71
+ self.MIPGap: Optional[float] = None # 表示多少的gap,0.10则表示10
72
+ self.EnableOutput = False
73
+ self.Checker: Literal['std', 'full', 'off'] = 'std'
74
+ '''
75
+ - 'std' (the default) performs type checks on arguments to methods; checks that numerical
76
+ arguments are numbers, but will not check for NaN or infinity.
77
+ - 'numeric' checks that numerical arguments are valid numbers, neither NaN nor
78
+ math.infinity
79
+ - 'full' performs all possible checks, the union of 'std' and 'numeric' checks.
80
+ - 'off' performs no checking at all. Disabling all checks might improve performance, but only when
81
+ it is safe to do so
82
+ '''
mipx/cplexcpsolver.py ADDED
@@ -0,0 +1,300 @@
1
+ # -*- coding: utf-8 -*-
2
+ # @Time : 2023/4/12 9:12
3
+ # @Author : luyi
4
+ """
5
+ 约束规划
6
+ """
7
+
8
+ from collections import defaultdict
9
+ from typing import Union, List, Dict, Tuple
10
+ from docplex.cp.model import CpoModel
11
+ from docplex.cp.model import interval_var, binary_var, minimize
12
+ from .constants import Vtype, ObjType, OptimizationStatus, CmpType
13
+ from .interface_ import IVar, IModel
14
+ from .tupledict import tupledict
15
+ from .utilx import is_list_or_tuple, get_combinations, \
16
+ name_str, check_bool_var, is_bool_var
17
+ from .variable import CPlexVar
18
+
19
+
20
+ Real = Union[float, int]
21
+ INFINITY = 1e+10
22
+
23
+
24
+ class CplexCpSolver(IModel):
25
+ """
26
+ 约束规划CPLEX 未实现
27
+
28
+ :param _type_ IModel: _description_
29
+ """
30
+
31
+ def __init__(self, name=""):
32
+ super().__init__()
33
+ self.name = name
34
+ self.__model = CpoModel(self.name)
35
+
36
+ self.__line_expr_object = defaultdict(list)
37
+ self._flag_objective_n = False
38
+ self._flag_objective = False
39
+
40
+ @property
41
+ def Infinity(self) -> float:
42
+ return INFINITY
43
+
44
+ def Sum(self, expr_array) -> 'IVar':
45
+
46
+ return self.__model.sum(expr_array) # type: ignore
47
+
48
+ def setHint(self, start: Dict[IVar, Real]):
49
+ raise RuntimeError('not implemented')
50
+
51
+ def setTimeLimit(self, time_limit_seconds: int):
52
+ self.Params.TimeLimit = time_limit_seconds
53
+
54
+ def wall_time(self) -> int:
55
+ solver_details: SolveDetails = self.__model.solve_details # type: ignore
56
+ return solver_details.time*1000
57
+
58
+ def iterations(self) -> Real:
59
+ solver_details: SolveDetails = self.__model.solve_details # type: ignore
60
+ return solver_details.nb_iterations
61
+
62
+ def nodes(self) -> Real:
63
+ solver_details: SolveDetails = self.__model.solve_details # type: ignore
64
+ return solver_details.nb_nodes_processed
65
+
66
+ def addVar(self, lb=None, ub=None,
67
+ vtype: Vtype = Vtype.CONTINUOUS, name: str = "") -> IVar:
68
+ """
69
+ Add a decision variable to a model.
70
+ :param lb: Lower bound for new variable.
71
+ :param ub: Upper bound for new variable.
72
+ :param vtype: variable type for new variable(Vtype.CONTINUOUS, Vtype.BINARY, Vtype.INTEGER).
73
+ :param name: Name for new variable.
74
+ :return: variable.
75
+ """
76
+
77
+ if vtype == Vtype.CONTINUOUS or vtype == Vtype.INTEGER:
78
+ var1 = interval_var(start=lb, end=ub, name=name)
79
+ else:
80
+ var1 = binary_var(name=name)
81
+ return var1
82
+
83
+ def addVars(self, *indices, lb=None, ub=None, vtype: Vtype = Vtype.CONTINUOUS,
84
+ name: str = "") -> tupledict:
85
+
86
+ li = []
87
+ for ind in indices:
88
+ if isinstance(ind, int):
89
+ ind = [i for i in range(ind)]
90
+ elif is_list_or_tuple(ind):
91
+ pass
92
+ elif isinstance(ind, str):
93
+ ind = [ind]
94
+ else:
95
+ raise ValueError("error input")
96
+ li.append(ind)
97
+ all_keys_tuple = get_combinations(li)
98
+ tu_dict = tupledict(
99
+ [[key, self.addVar(lb, ub, vtype, name_str(name, key))] for key in all_keys_tuple])
100
+ return tu_dict
101
+
102
+ def getVars(self) -> List[IVar]:
103
+ raise RuntimeError("not implemented")
104
+
105
+ def getVar(self, i) -> IVar:
106
+ return self.__model.get_all_variables() # type: ignore
107
+
108
+ def addConstr(self, lin_expr, name=""):
109
+ self.__model.add_constraint(lin_expr)
110
+
111
+ def addConstrs(self, lin_exprs, name=""):
112
+ # 检查下是否可以迭代。
113
+ self.__model.add(lin_exprs)
114
+
115
+ def setObjective(self, expr):
116
+ self._flag_objective = True
117
+ if self._flag_objective_n:
118
+ raise RuntimeError(
119
+ "setObjective and setObjectiveN can only be used for one of them")
120
+ self.__model.add(minimize(expr))
121
+
122
+ def setObjectiveN(self, expr, index: int, priority=None, weight: float = 1, name: str = ""):
123
+ """
124
+ :param expr:
125
+ :param index:
126
+ :param priority:
127
+ :param weight:
128
+ :param name:
129
+ :return:
130
+ """
131
+ self._flag_objective_n = True
132
+ if self._flag_objective:
133
+ raise RuntimeError(
134
+ "setObjective and setObjectiveN can only be used for one of them")
135
+
136
+ self.__line_expr_object['exprs'].append(expr)
137
+ self.__line_expr_object['priority'].append(priority)
138
+ self.__line_expr_object['weight'].append(weight)
139
+
140
+ def addGenConstrAnd(self, resvar, varList: List[IVar], name=""):
141
+ """
142
+ 和 addGenConstrAnd(y, [x1,x2])
143
+ :param resvar:
144
+ :param varList:
145
+ :param name:
146
+ :return:
147
+ """
148
+
149
+ self.addConstr(resvar == self.__model.logical_and(*varList))
150
+
151
+ def addGenConstrOr(self, resvar: IVar, varList: List[IVar], name=""):
152
+ self.addConstr(resvar == self.__model.logical_or(*varList))
153
+
154
+ def addGenConstrXOr(self, resvar: IVar, varList: List[IVar], name=""):
155
+ if len(varList) != 2:
156
+ raise ValueError("length of vars must be 2")
157
+ check_bool_var(resvar, varList)
158
+ self.addConstr(resvar >= varList[0] - varList[1])
159
+ self.addConstr(resvar >= varList[1] - varList[0])
160
+ self.addConstr(resvar <= varList[0] + varList[1])
161
+ self.addConstr(resvar <= 2 - varList[0] - varList[1])
162
+
163
+ def addGenConstrPWL(self, var_y: IVar, var_x: IVar, x_range: List[float], y_value: List[float], name=""):
164
+ pass
165
+
166
+ def addGenConstrIndicator(self, binvar: IVar, binval: bool, lhs: IVar, sense: CmpType, rhs: int, M,
167
+ name: str = ""):
168
+ # TODO:
169
+ raise RuntimeError("not implemented")
170
+
171
+ def addIndicator(self, binvar: IVar, binval: bool, expr,
172
+ name=None):
173
+ if name == "":
174
+ name = None
175
+ self.__model.add_indicator(binvar, expr, binval, name)
176
+
177
+ def addGenConstrAbs(self, resvar, var_abs: IVar, M, name=""):
178
+ self.addConstr(self.__model.abs(var_abs) == resvar)
179
+
180
+ def addConstrMultiply(self, z: IVar, l: Tuple[IVar, IVar], name=""):
181
+ """x * y = z"""
182
+ super().addConstrMultiply(z, l)
183
+ x = l[0]
184
+ y = l[1]
185
+ if not is_bool_var(x) and not is_bool_var(y):
186
+ raise RuntimeError("At least one binary variable is required.")
187
+ if is_bool_var(y):
188
+ x, y = y, x
189
+ M = y.Ub
190
+ self.addConstr(z <= y)
191
+ self.addConstr(z <= x * M)
192
+ self.addConstr(z >= y + (x - 1) * M)
193
+
194
+ def addRange(self, expr, min_value: Union[float, int], max_value: Union[float, int], name=''):
195
+ self.__model.add_range(min_value, expr, max_value, rng_name=name)
196
+
197
+ def addConstrOr(self, constrs: List, ok_num: int = 1, cmpType: CmpType = CmpType.EQUAL, name: str = "", M=None):
198
+ """
199
+ 约束的满足情况
200
+
201
+ :param constr: 所有的约束
202
+ :param ok_num: 需要满足的个数,具体则根据cmpType
203
+ :param cmpType: CmpType.LESS_EQUAL CmpType.EQUAL,CmpType.GREATER_EQUAL
204
+ :param name: 名称
205
+ :return:
206
+ """
207
+ constr_num = len(constrs)
208
+ x = []
209
+ for i in range(constr_num):
210
+ x.append(self.addVar(vtype=Vtype.BINARY))
211
+ constr = constrs[i]
212
+ lb, ub = constr.Bounds()
213
+ expr = constr.Expression()
214
+ tempM = 100000000
215
+ if M is not None:
216
+ tempM = M
217
+ if lb > -INFINITY: # 若大于
218
+ self.addConstr(expr + tempM * (1 - x[i]) >= lb)
219
+ if ub < INFINITY:
220
+ self.addConstr(expr - tempM * (1 - x[i]) <= ub)
221
+ if cmpType == CmpType.EQUAL:
222
+ self.addConstr(self.Sum(x) == ok_num)
223
+ elif cmpType == CmpType.GREATER_EQUAL:
224
+ self.addConstr(self.Sum(x) >= ok_num)
225
+ elif cmpType == CmpType.LESS_EQUAL:
226
+ self.addConstr(self.Sum(x) <= ok_num) # type: ignore
227
+ else:
228
+ raise Exception("error value of cmpType")
229
+
230
+ def addKpi(self, kpi_arg, name=None) -> IVar: # 为了统一,暂时考虑
231
+ return self.__model.add_kpi(kpi_arg, name) # type: ignore
232
+
233
+ def numVars(self) -> int:
234
+ return self.__model.number_of_variables
235
+
236
+ def numConstraints(self) -> int:
237
+ return self.__model.number_of_constraints
238
+
239
+ def write(self, filename: str, obfuscated=False):
240
+ filename = filename.lower()
241
+ if filename.endswith(".lp"):
242
+ self.__model.export_as_lp(filename)
243
+ elif filename.endswith(".mps"):
244
+ self.__model.export_as_mps(filename)
245
+ elif filename.endswith(".proto"):
246
+ raise TypeError(".proto 导出异常,待修复")
247
+
248
+ def read(self, path: str):
249
+ self.clear()
250
+ m = ModelReader.read_model(path)
251
+ self.__model = m
252
+
253
+ @property
254
+ def ObjVal(self) -> Real:
255
+ return self.__model.objective_value
256
+
257
+ def optimize(self, obj_type: ObjType = ObjType.MINIMIZE) -> OptimizationStatus:
258
+ if self.Params.TimeLimit:
259
+ self.setTimeLimit(self.Params.TimeLimit)
260
+ if self.Params.MIPGap:
261
+ self.__model.parameters.mip.tolerances.mipgap = self.Params.MIPGap # type: ignore
262
+
263
+ if self._flag_objective_n:
264
+ self.__model.set_multi_objective(
265
+ 'min' if obj_type is ObjType.MINIMIZE else 'max', self.__line_expr_object['exprs'], self.__line_expr_object['priority'], self.__line_expr_object['weight'])
266
+ status: SolveSolution = self.__model.solve(
267
+ log_output=self.Params.EnableOutput, checker=self.Params.Checker) # type: ignore
268
+ if status:
269
+ if status.is_feasible_solution or status.is_valid_solution:
270
+ result = OptimizationStatus.OPTIMAL
271
+ else:
272
+ result = OptimizationStatus.FEASIBLE
273
+ else:
274
+ result = OptimizationStatus.ERROR
275
+ return result
276
+
277
+ def clear(self):
278
+ self.__model.clear()
279
+
280
+ def close(self):
281
+ self.__model.end()
282
+ # 独有。
283
+
284
+ def addNoOverlap(self, interval_vars, M):
285
+ """
286
+ 相邻不重复。
287
+
288
+ :param interval_vars:
289
+ :return:
290
+ """
291
+ raise RuntimeError("not implemented")
292
+
293
+ def newIntervalVar(self, start, size, end, name=""):
294
+ raise RuntimeError("not implemented")
295
+
296
+ def valueExpression(self, expression):
297
+ raise RuntimeError("not implemented")
298
+
299
+ def setNumThreads(self, num_theads: int):
300
+ self.__model.context.cplex_parameters.threads = num_theads