本文整理汇总了Python中cylp.cy.CyClpSimplex.addVariable方法的典型用法代码示例。如果您正苦于以下问题:Python CyClpSimplex.addVariable方法的具体用法?Python CyClpSimplex.addVariable怎么用?Python CyClpSimplex.addVariable使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类cylp.cy.CyClpSimplex
的用法示例。
在下文中一共展示了CyClpSimplex.addVariable方法的14个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: QPModel
# 需要导入模块: from cylp.cy import CyClpSimplex [as 别名]
# 或者: from cylp.cy.CyClpSimplex import addVariable [as 别名]
def QPModel(self, addW=False):
A = self.A
c = self.c
s = CyClpSimplex()
x = s.addVariable('x', self.nCols)
if addW:
w = s.addVariable('w', self.nCols)
s += A * x >= 1
n = self.nCols
if not addW:
s += 0 <= x <= 1
else:
s += x + w == 1
s += 0 <= w <= 1
## s += -1 <= x <= 1
s.objective = c * x
if addW:
G = sparse.lil_matrix((2*n, 2*n))
for i in xrange(n/2, n): #xrange(n-1):
G[i, i] = 1
G[2*n-1, 2*n-1] = 10**-10
else:
G = sparse.lil_matrix((n, n))
for i in xrange(n/2, n): #xrange(n-1):
G[i, i] = 1
s.Hessian = G
return s
示例2: test2
# 需要导入模块: from cylp.cy import CyClpSimplex [as 别名]
# 或者: from cylp.cy.CyClpSimplex import addVariable [as 别名]
def test2(self):
'Same as test1, but use cylp indirectly.'
s = CyClpSimplex()
x = s.addVariable('x', 3)
A = np.matrix([[1,2,3], [1,1,1]])
b = CyLPArray([5, 3])
s += A * x == b
s += x >= 0
s.objective = 1 * x[0] + 1 * x[1] + 1.1 * x[2]
# Solve it a first time
s.primal()
sol = s.primalVariableSolution['x']
self.assertTrue((abs(sol - np.array([1,2,0]) ) <= 10**-6).all())
# Add a cut
s.addConstraint(x[0] >= 1.1)
s.primal()
sol = s.primalVariableSolution['x']
self.assertTrue((abs(sol - np.array([1.1, 1.8, 0.1]) ) <= 10**-6).all())
# Change the objective function
c = csr_matrixPlus([[1, 10, 1.1]]).T
s.objective = c.T * x
s.primal()
sol = s.primalVariableSolution['x']
self.assertTrue((abs(sol - np.array([2, 0, 1]) ) <= 10**-6).all())
示例3: read_instance
# 需要导入模块: from cylp.cy import CyClpSimplex [as 别名]
# 或者: from cylp.cy.CyClpSimplex import addVariable [as 别名]
def read_instance(module_name = None, file_name = None):
if module_name is not None:
lp = CyClpSimplex()
mip = ilib.import_module(module_name)
A = np.matrix(mip.A)
#print np.linalg.cond(A)
b = CyLPArray(mip.b)
#Warning: At the moment, you must put bound constraints in explicitly for split cuts
x_l = CyLPArray([0 for _ in range(mip.numVars)])
x = lp.addVariable('x', mip.numVars)
lp += x >= x_l
try:
x_u = CyLPArray(getattr(mip, 'x_u'))
lp += x <= x_u
except:
pass
lp += (A * x <= b if mip.sense[1] == '<=' else
A * x >= b)
c = CyLPArray(mip.c)
lp.objective = -c * x if mip.sense[0] == 'Max' else c * x
return lp, x, mip.A, mip.b, mip.sense[1], mip.integerIndices
elif file_name is not None:
lp = CyClpSimplex()
m = lp.extractCyLPModel(file_name)
x = m.getVarByName('x')
integerIndices = [i for (i, j) in enumerate(lp.integerInformation) if j == True]
infinity = lp.getCoinInfinity()
sense = None
for i in range(lp.nRows):
if lp.constraintsLower[i] > -infinity:
if sense == '<=':
print "Function does not support mixed constraint..."
break
else:
sense = '>='
b = lp.constraintsLower
if lp.constraintsUpper[i] < infinity:
if sense == '>=':
print "Function does not support mixed constraint..."
break
else:
sense = '<='
b = lp.constraintsUpper
return lp, x, lp.coefMatrix, b, sense, integerIndices
else:
print "No file or module name specified..."
return None, None, None, None, None, None
示例4: model
# 需要导入模块: from cylp.cy import CyClpSimplex [as 别名]
# 或者: from cylp.cy.CyClpSimplex import addVariable [as 别名]
def model(self):
A = self.A
c = self.c
s = CyClpSimplex()
x = s.addVariable('x', self.nCols)
s += A * x >= 1
s += 0 <= x <= 1
s.objective = c * x
return s
示例5: test_removeVar2
# 需要导入模块: from cylp.cy import CyClpSimplex [as 别名]
# 或者: from cylp.cy.CyClpSimplex import addVariable [as 别名]
def test_removeVar2(self):
s = CyClpSimplex()
fp = os.path.join(currentFilePath, '../../input/p0033.mps')
s.extractCyLPModel(fp)
y = s.addVariable('y', 3)
s.primal()
x = s.getVarByName('x')
s.addConstraint(x[1] + y[1] >= 1.2)
#s.primal()
s.removeVariable('x')
s.primal()
s = s.primalVariableSolution
self.assertTrue((s['y'] - np.array([0, 1.2, 0]) <= 10**-6).all())
示例6: test_multiDim
# 需要导入模块: from cylp.cy import CyClpSimplex [as 别名]
# 或者: from cylp.cy.CyClpSimplex import addVariable [as 别名]
def test_multiDim(self):
from cylp.cy import CyClpSimplex
from cylp.py.modeling.CyLPModel import CyLPArray
s = CyClpSimplex()
x = s.addVariable('x', (5, 3, 6))
s += 2 * x[2, :, 3].sum() + 3 * x[0, 1, :].sum() >= 5
s += 0 <= x <= 1
c = CyLPArray(range(18))
s.objective = c * x[2, :, :] + c * x[0, :, :]
s.primal()
sol = s.primalVariableSolution['x']
self.assertTrue(abs(sol[0, 1, 0] - 1) <= 10**-6)
self.assertTrue(abs(sol[2, 0, 3] - 1) <= 10**-6)
示例7: test_ArrayIndexing
# 需要导入模块: from cylp.cy import CyClpSimplex [as 别名]
# 或者: from cylp.cy.CyClpSimplex import addVariable [as 别名]
def test_ArrayIndexing(self):
from cylp.cy import CyClpSimplex
from cylp.py.modeling.CyLPModel import CyLPArray
s = CyClpSimplex()
x = s.addVariable('x', (5, 3, 6))
s += 2 * x[2, :, 3].sum() + 3 * x[0, 1, :].sum() >= 5
s += x[1, 2, [0, 3, 5]] - x[2, 1, np.array([1, 2, 4])] == 1
s += 0 <= x <= 1
c = CyLPArray(range(18))
s.objective = c * x[2, :, :] + c * x[0, :, :]
s.primal()
sol = s.primalVariableSolution['x']
self.assertTrue(abs(sol[1, 2, 0] - 1) <= 10**-6)
self.assertTrue(abs(sol[1, 2, 3] - 1) <= 10**-6)
self.assertTrue(abs(sol[1, 2, 5] - 1) <= 10**-6)
示例8: test_onlyBounds2
# 需要导入模块: from cylp.cy import CyClpSimplex [as 别名]
# 或者: from cylp.cy.CyClpSimplex import addVariable [as 别名]
def test_onlyBounds2(self):
s = CyClpSimplex()
x = s.addVariable('x', 3)
y = s.addVariable('y', 2)
s += y >= 1
s += 2 <= x <= 4
c = CyLPArray([1., -2., 3.])
s.objective = c * x + 2 * y[0] + 2 * y[1]
s.primal()
sol = np.concatenate((s.primalVariableSolution['x'],
s.primalVariableSolution['y']))
self.assertTrue((abs(sol -
np.array([2, 4, 2, 1, 1]) ) <= 10**-6).all())
示例9: test_multiDim_Cbc_solve
# 需要导入模块: from cylp.cy import CyClpSimplex [as 别名]
# 或者: from cylp.cy.CyClpSimplex import addVariable [as 别名]
def test_multiDim_Cbc_solve(self):
from cylp.cy import CyClpSimplex
from cylp.py.modeling.CyLPModel import CyLPArray
s = CyClpSimplex()
x = s.addVariable('x', (5, 3, 6))
s += 2 * x[2, :, 3].sum() + 3 * x[0, 1, :].sum() >= 5.5
s += 0 <= x <= 2.2
c = CyLPArray(range(18))
s.objective = c * x[2, :, :] + c * x[0, :, :]
s.setInteger(x)
cbcModel = s.getCbcModel()
cbcModel.solve()
sol_x = cbcModel.primalVariableSolution['x']
self.assertTrue(abs(sol_x[0, 1, 0] - 1) <= 10**-6)
self.assertTrue(abs(sol_x[2, 0, 3] - 2) <= 10**-6)
示例10: read_instance
# 需要导入模块: from cylp.cy import CyClpSimplex [as 别名]
# 或者: from cylp.cy.CyClpSimplex import addVariable [as 别名]
def read_instance(module_name = True, file_name = None):
if module_name:
lp = CyClpSimplex()
mip = ilib.import_module(module_name)
A = np.matrix(mip.A)
#print np.linalg.cond(A)
b = CyLPArray(mip.b)
#We assume variables have zero lower bounds
x_l = CyLPArray([0 for _ in range(mip.numVars)])
x = lp.addVariable('x', mip.numVars)
lp += x >= x_l
try:
x_u = CyLPArray(getattr(mip, 'x_u'))
lp += x <= x_u
except:
pass
lp += (A * x <= b if mip.sense[1] == '<=' else
A * x >= b)
c = CyLPArray(mip.c)
lp.objective = -c * x if mip.sense[0] == 'Max' else c * x
return lp, x, mip.A, mip.b, mip.sense, mip.integerIndices
else:
#TODO Change sense of inequalities so they are all the same
# by explicitly checking lp.constraintsUpper and lp.constraintsLower
#Warning: Reading MP not well tested
lp.extractCyLPModel(file_name)
x = lp.cyLPModel.getVarByName('x')
sense = ('Min', '>=')
return lp, x, None, None, sense, integerIndices
示例11: isinstance
# 需要导入模块: from cylp.cy import CyClpSimplex [as 别名]
# 或者: from cylp.cy.CyClpSimplex import addVariable [as 别名]
#if isinstance(key, tuple):
if val == 0: # See if necessary to use a tolerance
return
self.sol[key] = val
def __repr__(self):
return repr(self.sol)
def getCoinInfinity():
return 1.79769313486e+308
if __name__ == '__main__':
from cylp.cy import CyClpSimplex
from cylp.py.modeling.CyLPModel import CyLPArray
s = CyClpSimplex()
x = s.addVariable('x', (5, 3, 6))
s += 2 * x[2, :, 3].sum() + 3 * x[0, 1, :].sum() >= 5
s += 0 <= x <= 1
c = CyLPArray(range(18))
s.objective = c * x[2, :, :] + c * x[0, :, :]
s.writeMps('/Users/mehdi/Desktop/test.mps')
s.primal()
sol = s.primalVariableSolution
print sol
#model = CyLPModel()
#
#x = model.addVariable('x', 5)
#y = model.addVariable('y', 4)
示例12: solve
# 需要导入模块: from cylp.cy import CyClpSimplex [as 别名]
# 或者: from cylp.cy.CyClpSimplex import addVariable [as 别名]
def solve(self, objective, constraints, cached_data,
warm_start, verbose, solver_opts):
"""Returns the result of the call to the solver.
Parameters
----------
objective : LinOp
The canonicalized objective.
constraints : list
The list of canonicalized cosntraints.
cached_data : dict
A map of solver name to cached problem data.
warm_start : bool
Not used.
verbose : bool
Should the solver print output?
solver_opts : dict
Additional arguments for the solver.
Returns
-------
tuple
(status, optimal value, primal, equality dual, inequality dual)
"""
# Import basic modelling tools of cylp
from cylp.cy import CyClpSimplex
from cylp.py.modeling.CyLPModel import CyLPArray
# Get problem data
data = self.get_problem_data(objective, constraints, cached_data)
c = data[s.C]
b = data[s.B]
A = data[s.A]
dims = data[s.DIMS]
n = c.shape[0]
solver_cache = cached_data[self.name()]
# Problem
model = CyClpSimplex()
# Variables
x = model.addVariable('x', n)
if self.is_mip(data):
for i in data[s.BOOL_IDX]:
model.setInteger(x[i])
for i in data[s.INT_IDX]:
model.setInteger(x[i])
# Constraints
# eq
model += A[0:dims[s.EQ_DIM], :] * x == b[0:dims[s.EQ_DIM]]
# leq
leq_start = dims[s.EQ_DIM]
leq_end = dims[s.EQ_DIM] + dims[s.LEQ_DIM]
model += A[leq_start:leq_end, :] * x <= b[leq_start:leq_end]
# no boolean vars available in cbc -> model as int + restrict to [0,1]
if self.is_mip(data):
for i in data[s.BOOL_IDX]:
model += 0 <= x[i] <= 1
# Objective
model.objective = c
# Build model & solve
status = None
if self.is_mip(data):
cbcModel = model.getCbcModel() # need to convert model
if not verbose:
cbcModel.logLevel = 0
# Add cut-generators (optional)
for cut_name, cut_func in six.iteritems(self.SUPPORTED_CUT_GENERATORS):
if cut_name in solver_opts and solver_opts[cut_name]:
module = importlib.import_module("cylp.cy.CyCgl")
funcToCall = getattr(module, cut_func)
cut_gen = funcToCall()
cbcModel.addCutGenerator(cut_gen, name=cut_name)
# solve
status = cbcModel.branchAndBound()
else:
if not verbose:
model.logLevel = 0
status = model.primal() # solve
results_dict = {}
results_dict["status"] = status
if self.is_mip(data):
results_dict["x"] = cbcModel.primalVariableSolution['x']
results_dict["obj_value"] = cbcModel.objectiveValue
else:
results_dict["x"] = model.primalVariableSolution['x']
results_dict["obj_value"] = model.objectiveValue
#.........这里部分代码省略.........
示例13: CyClpSimplex
# 需要导入模块: from cylp.cy import CyClpSimplex [as 别名]
# 或者: from cylp.cy.CyClpSimplex import addVariable [as 别名]
if p is not None:
if CYLP_INSTALLED:
lp = CyClpSimplex()
A = np.matrix(p.hrep.A)
b = CyLPArray(p.hrep.b)
print(A)
print(b)
if LP.numVars == 2:
disp_polyhedron(A = A, b = b)
x = lp.addVariable('x', LP.numVars)
if LP.sense[0] == '>=':
lp += A * x >= b
else:
lp += A * x <= b
#lp += x >= 0
c = CyLPArray(LP.c)
# We are maximizing, so negate objective
if LP.sense[1] == 'Min':
lp.objective = c * x
else:
lp.objective = -c * x
lp.logLevel = 0
lp.primal(startFinishOptions = 'x')
示例14: __init__
# 需要导入模块: from cylp.cy import CyClpSimplex [as 别名]
# 或者: from cylp.cy.CyClpSimplex import addVariable [as 别名]
def __init__(self, module_name = None, file_name = None,
A = None, b = None, c = None,
points = None, rays = None,
sense = None, integerIndices = None,
numVars = None):
if file_name is not None:
# We got a file name, so ignore everything else and read in the instance
lp = CyClpSimplex()
lp.extractCyLPModel(file_name)
self.integerIndices = [i for (i, j) in enumerate(lp.integerInformation) if j == True]
infinity = lp.getCoinInfinity()
A = lp.coefMatrix
b = CyLPArray([0 for _ in range(lp.nRows)])
for i in range(lp.nRows):
if lp.constraintsLower[i] > -infinity:
if lp.constraintsUpper[i] < infinity:
raise Exception('Cannot handle ranged constraints')
b[i] = -lp.constraintsLower[i]
for j in range(lp.nCols):
A[i, j] = -A[i, j]
elif lp.constraintsUpper[i] < infinity:
b[i] = lp.constraintsUpper[i]
else:
raise Exception('Constraint with no bounds detected')
x = lp.addVariable('x', lp.nCols)
lp += A * x <= b
lp += x <= lp.variablesUpper
lp += x >= lp.variablesLower
lp.objective = lp.objective
self.sense = '<='
numVars = lp.nCols
else:
min_or_max = None
if module_name is not None:
# We got a module name, read the data from there
mip = ilib.import_module(module_name)
self.A = mip.A if hasattr(mip, 'A') else None
self.b = mip.b if hasattr(mip, 'b') else None
points = mip.points if hasattr(mip, 'points') else None
rays = mip.rays if hasattr(mip, 'rays') else None
self.c = mip.c if hasattr(mip, 'c') else None
self.sense = mip.sense[1] if hasattr(mip, 'sense') else None
min_or_max = mip.sense[0] if hasattr(mip, 'sense') else None
self.integerIndices = mip.integerIndices if hasattr(mip, 'integerIndices') else None
x_u = CyLPArray(mip.x_u) if hasattr(mip, 'x_u') else None
numVars = mip.numVars if hasattr(mip, 'numVars') else None
self.x_sep = mip.x_sep if hasattr(mip, 'x_sep') else None
if numVars is None and mip.A is not None:
numVars = len(mip.A)
if numVars is None:
raise "Must specify number of variables when problem is not"
else:
self.A = A
self.b = b
self.c = c
self.points = points
self.rays = rays
if sense is not None:
self.sense = sense[1]
min_or_max = sense[0]
self.integerIndices = integerIndices
x_u = None
lp = CyClpSimplex()
if self.A is not None:
A = np.matrix(self.A)
b = CyLPArray(self.b)
elif numVars <= 2 and GRUMPY_INSTALLED:
p = Polyhedron2D(points = points, rays = rays)
A = np.matrix(p.hrep.A)
b = np.matrix(p.hrep.b)
else:
raise "Must specify problem in inequality form with more than two variables\n"
#Warning: At the moment, you must put bound constraints in explicitly for split cuts
x_l = CyLPArray([0 for _ in range(numVars)])
x = lp.addVariable('x', numVars)
lp += x >= x_l
if x_u is not None:
lp += x <= x_u
lp += (A * x <= b if self.sense == '<=' else
A * x >= b)
c = CyLPArray(self.c)
if min_or_max == 'Max':
lp.objective = -c * x
else:
lp.objective = c * x
self.lp = lp
self.x = x