-
Notifications
You must be signed in to change notification settings - Fork 69
/
Copy pathCyCbcModel.pyx
294 lines (240 loc) · 9.79 KB
/
CyCbcModel.pyx
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
# cython: embedsignature=True
from itertools import product
try:
from itertools import izip
except ImportError: # Python 3 does not have izip, use zip
izip = zip
from cylp.py.mip import NodeCompareBase
from cylp.py.modeling.CyLPModel import CyLPSolution
from cylp.cy.CyCutGeneratorPythonBase cimport CyCutGeneratorPythonBase
from libcpp cimport bool
cdef int RunTest(void* ptr, CppICbcNode*x, CppICbcNode*y):
obj = <object> ptr
return obj.compare(CyCbcNode().setCppSelf(x),
CyCbcNode().setCppSelf(y))
cdef bool RunNewSolution(void* ptr, CppICbcModel* model,
double objectiveAtContinuous,
int numberInfeasibilitiesAtContinuous):
obj = <object> ptr
return obj.newSolution(CyCbcModel().setCppSelf(model),
objectiveAtContinuous,
numberInfeasibilitiesAtContinuous)
cdef int RunEvery1000Nodes(void* ptr, CppICbcModel* model, int numberNodes):
obj = <object> ptr
return obj.every1000Nodes(CyCbcModel().setCppSelf(model),
numberNodes)
# Understandable messages to translate what branchAndBound() returns
problemStatus = ['solution', 'relaxation infeasible',
'stopped on gap', 'stopped on nodes', 'stopped on time',
'stopped on user event', 'stopped on solutions'
'linear relaxation unbounded', 'unset']
cdef class CyCbcModel:
'''
Interfaces ``CbcModel``. To solve a first you create a
:class:`cylp.cy.CyClpSimplex` object either
by reading it from an ``mps`` file using
:func:`CyClpSimplex.readMps() <cylp.cy.CyClpSimplex.CyClpSimplex.readMps>`
or by using cylp modeling tool
:mod:`cylp.py.modeling.CyLPModel`. Then you ask the object for a
``CyCbcModel`` which is capable solving MIPs using B&B
**Usage**
>>> import numpy as np
>>> from cylp.cy import CyCbcModel, CyClpSimplex
>>> from cylp.py.modeling.CyLPModel import CyLPModel, CyLPArray
>>> model = CyLPModel()
>>>
>>> x = model.addVariable('x', 3, isInt=True)
>>> y = model.addVariable('y', 2)
>>>
>>> A = np.matrix([[1., 2., 0],[1., 0, 1.]])
>>> B = np.matrix([[1., 0, 0], [0, 0, 1.]])
>>> D = np.matrix([[1., 2.],[0, 1]])
>>> a = CyLPArray([5, 2.5])
>>> b = CyLPArray([4.2, 3])
>>> x_u= CyLPArray([2., 3.5])
>>>
>>> model += A*x <= a
>>> model += 2 <= B * x + D * y <= b
>>> model += y >= 0
>>> model += 1.1 <= x[1:3] <= x_u
>>>
>>> c = CyLPArray([1., -2., 3.])
>>> model.objective = c * x + 2 * y.sum()
>>>
>>> s = CyClpSimplex(model)
>>>
>>> cbcModel = s.getCbcModel()
>>>
>>> cbcModel.solve()
0
>>> print (cbcModel.status)
'solution'
>>> sol_x = cbcModel.primalVariableSolution['x']
>>>
>>> (abs(sol_x - np.array([0, 2, 2])) <= 10**-6).all()
True
'''
def __cinit__(self, cyLPModel=None):
self.cyLPModel = cyLPModel
self.cutGenerators = []
def __dealloc__(self):
for generator in self.cutGenerators:
Py_DECREF(generator)
try:
if self.CppSelf:
del self.CppSelf
except AttributeError:
pass
cdef setCppSelf(self, CppICbcModel* cppmodel):
self.CppSelf = cppmodel
return self
cdef setClpModel(self, clpmodel):
self.clpModel = clpmodel
return self
def setNodeCompare(self, nodeCompareObject):
if not isinstance(nodeCompareObject, NodeCompareBase):
raise TypeError('setNodeCompare argument should be a ' \
'NodeCompareBase object. Got %s' %
nodeCompareObject.__class__)
self.CppSelf.setNodeCompare(<PyObject*>nodeCompareObject,
RunTest, RunNewSolution, RunEvery1000Nodes)
cpdef addCutGenerator(self, CyCglCutGenerator generator,
howOften=1, name="", normal=True, atSolution=False,
infeasible=False, howOftenInSub=-100, whatDepth=-1,
whatDepthInSub=-1):
self.cutGenerators.append(generator)
Py_INCREF(generator)
if isinstance(name, str):
# Cast strings/unicode to bytes
name = name.encode('utf-8')
self.CppSelf.addCutGenerator(generator.CppSelf, howOften,
name, normal, atSolution,
infeasible, howOftenInSub, whatDepth,
whatDepthInSub)
def addPythonCutGenerator(self, pythonCutGeneratorObject,
howOften=1, name="", normal=True, atSolution=False,
infeasible=False, howOftenInSub=-100, whatDepth=-1,
whatDepthInSub=-1):
cdef CyCutGeneratorPythonBase generator = \
CyCutGeneratorPythonBase(pythonCutGeneratorObject)
generator.cyLPModel = self.cyLPModel
self.CppSelf.addCutGenerator(<CppCglCutGenerator*>generator.CppSelf,
howOften, name, normal, atSolution,
infeasible, howOftenInSub, whatDepth,
whatDepthInSub)
def solve(self):
'''
Call CbcMain. Solve the problem using the same parameters used by CbcSolver.
Equivalent to solving the model from the command line using cbc's binary.
'''
return self.CppSelf.cbcMain()
property status:
def __get__(self):
# secondaryStatus() should be used instead of status() (??)
#if self.isRelaxationInfeasible():
# return problemStatus[1]
#if self.isRelaxationAbondoned():
# return 'relaxation abondoned'
#return problemStatus[self.CppSelf.status()]
return problemStatus[self.CppSelf.secondaryStatus()]
property logLevel:
def __get__(self):
return self.CppSelf.logLevel()
def __set__(self, value):
self.CppSelf.setLogLevel(value)
def isRelaxationInfeasible(self):
return self.CppSelf.isInitialSolveProvenPrimalInfeasible()
def isRelaxationDualInfeasible(self):
return self.CppSelf.isInitialSolveProvenDualInfeasible()
def isRelaxationOptimal(self):
return self.CppSelf.isInitialSolveProvenOptimal()
def isRelaxationAbondoned(self):
return self.CppSelf.isInitialSolveAbandoned()
property osiSolverInteface:
def __get__(self):
cdef CyOsiSolverInterface osi = CyOsiSolverInterface()
osi.setCppSelf(self.CppSelf.solver())
return osi
property primalVariableSolution:
def __get__(self):
ret = <object>self.CppSelf.getPrimalVariableSolution()
if self.cyLPModel:
m = self.cyLPModel
inds = m.inds
d = {}
for v in inds.varIndex.keys():
d[v] = ret[inds.varIndex[v]]
var = m.getVarByName(v)
if var.dims:
d[v] = CyLPSolution()
dimRanges = [range(i) for i in var.dims]
for element in product(*dimRanges):
d[v][element] = ret[var.__getitem__(element).indices[0]]
ret = d
else:
names = self.clpModel.variableNames
if names:
d = CyLPSolution()
for i in range(len(names)):
d[names[i]] = ret[i]
ret = d
return ret
property solutionCount:
def __get__(self):
return self.CppSelf.getSolutionCount()
property numberHeuristicSolutions:
def __get__(self):
return self.CppSelf.getNumberHeuristicSolutions()
property nodeCount:
def __get__(self):
return self.CppSelf.getNodeCount()
property objectiveValue:
def __get__(self):
return self.CppSelf.getObjValue()
property bestPossibleObjValue:
def __get__(self):
return self.CppSelf.getBestPossibleObjValue()
property numberObjects:
def __get__(self):
return self.CppSelf.numberObjects()
property integerTolerance:
def __get__(self):
return self.CppSelf.getIntegerTolerance()
def __set__(self, value):
self.CppSelf.setIntegerTolerance(value)
property maximumSeconds:
def __get__(self):
return self.CppSelf.getMaximumSeconds()
def __set__(self, value):
self.CppSelf.setMaximumSeconds(value)
property maximumNodes:
def __get__(self):
return self.CppSelf.getMaximumNodes()
def __set__(self, value):
self.CppSelf.setMaximumNodes(value)
property numberThreads:
def __get__(self):
return self.CppSelf.getNumberThreads()
def __set__(self, value):
self.CppSelf.setNumberThreads(value)
property allowableGap:
def __get__(self):
return self.CppSelf.getAllowableGap()
def __set__(self, value):
self.CppSelf.setAllowableGap(value)
property allowableFractionGap:
def __get__(self):
return self.CppSelf.getAllowableFractionGap()
def __set__(self, value):
self.CppSelf.setAllowableFractionGap(value)
property allowablePercentageGap:
def __get__(self):
return self.CppSelf.getAllowablePercentageGap()
def __set__(self, value):
self.CppSelf.setAllowablePercentageGap(value)
property maximumSolutions:
def __get__(self):
return self.CppSelf.getMaximumSolutions()
def __set__(self, value):
self.CppSelf.setMaximumSolutions(value)
#TODO: add access to solver: getLower, getUpper,...