本文整理匯總了Python中cplex.Cplex方法的典型用法代碼示例。如果您正苦於以下問題:Python cplex.Cplex方法的具體用法?Python cplex.Cplex怎麽用?Python cplex.Cplex使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在類cplex
的用法示例。
在下文中一共展示了cplex.Cplex方法的11個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。
示例1: __init__
# 需要導入模塊: import cplex [as 別名]
# 或者: from cplex import Cplex [as 別名]
def __init__(self, cplex=None):
if not _HAS_CPLEX:
raise NameError('CPLEX is not installed. '
'See https://www.ibm.com/support/knowledgecenter/'
'SSSA5P_12.8.0/ilog.odms.studio.help/Optimization_Studio/'
'topics/COS_home.html')
if cplex:
self._model = Cplex(cplex._model)
else:
self._model = Cplex()
self._init_lin()
# to avoid a variable with index 0
self._model.variables.add(names=['_dummy_'], types=[self._model.variables.type.continuous])
self._var_id = {'_dummy_': 0}
示例2: solve_with_cplex
# 需要導入模塊: import cplex [as 別名]
# 或者: from cplex import Cplex [as 別名]
def solve_with_cplex(path):
import cplex
problem = cplex.Cplex()
problem.parameters.read.datacheck.set(0)
problem.set_results_stream("%s_cplex.log" % path)
problem.read(("%s.lp" % path).encode("utf8")) # unicode conversion required by CPLEX (undocumented)
problem.solve()
if problem.solution.get_status() != 103: # No solution exists
return {
"distances": problem.solution.get_objective_value(),
"names": problem.variables.get_names(),
"assigned": problem.solution.get_values(),
}
示例3: add_mip_starts
# 需要導入模塊: import cplex [as 別名]
# 或者: from cplex import Cplex [as 別名]
def add_mip_starts(mip, indices, pool, max_mip_starts = float('inf'), mip_start_effort_level = 4):
"""
Parameters
----------
mip - RiskSLIM surrogate MIP
indices - indices of RiskSLIM surrogate MIP
pool - solution pool
max_mip_starts - max number of mip starts to add (optional; default is add all)
mip_start_effort_level - effort that CPLEX will spend trying to fix (optional; default is 4)
Returns
-------
"""
# todo remove suboptimal using pool filter
assert isinstance(mip, Cplex)
try:
obj_cutoff = mip.parameters.mip.tolerances.uppercutoff.get()
except:
obj_cutoff = float('inf')
pool = pool.distinct().sort()
n_added = 0
for objval, rho in zip(pool.objvals, pool.solutions):
if np.less_equal(objval, obj_cutoff):
mip_start_name = "mip_start_" + str(n_added)
mip_start_obj, _ = convert_to_risk_slim_cplex_solution(rho = rho, indices = indices, objval = objval)
mip_start_obj = cast_mip_start(mip_start_obj, mip)
mip.MIP_starts.add(mip_start_obj, mip_start_effort_level, mip_start_name)
n_added += 1
if n_added >= max_mip_starts:
break
return mip
示例4: cast_mip_start
# 需要導入模塊: import cplex [as 別名]
# 或者: from cplex import Cplex [as 別名]
def cast_mip_start(mip_start, cpx):
"""
casts the solution values and indices in a Cplex SparsePair
Parameters
----------
mip_start cplex SparsePair
cpx Cplex
Returns
-------
Cplex SparsePair where the indices are integers and the values for each variable match the variable type specified in CPLEX Object
"""
assert isinstance(cpx, Cplex)
assert isinstance(mip_start, SparsePair)
vals = list(mip_start.val)
idx = np.array(list(mip_start.ind), dtype = int).tolist()
types = cpx.variables.get_types(idx)
for j, t in enumerate(types):
if t in ['B', 'I']:
vals[j] = int(vals[j])
elif t in ['C']:
vals[j] = float(vals[j])
return SparsePair(ind = idx, val = vals)
示例5: findSolutionValues
# 需要導入模塊: import cplex [as 別名]
# 或者: from cplex import Cplex [as 別名]
def findSolutionValues(self, lp):
lp.cplex_status = lp.solverModel.solution.get_status()
lp.status = self.CplexLpStatus.get(lp.cplex_status, LpStatusUndefined)
var_names = [var.name for var in lp.variables()]
con_names = [con for con in lp.constraints]
try:
objectiveValue = lp.solverModel.solution.get_objective_value()
variablevalues = dict(zip(var_names, lp.solverModel.solution.get_values(var_names)))
lp.assignVarsVals(variablevalues)
constraintslackvalues = dict(zip(con_names, lp.solverModel.solution.get_linear_slacks(con_names)))
lp.assignConsSlack(constraintslackvalues)
if lp.solverModel.get_problem_type == cplex.Cplex.problem_type.LP:
variabledjvalues = dict(zip(var_names, lp.solverModel.solution.get_reduced_costs(var_names)))
lp.assignVarsDj(variabledjvalues)
constraintpivalues = dict(zip(con_names, lp.solverModel.solution.get_dual_values(con_names)))
lp.assignConsPi(constraintpivalues)
except cplex.exceptions.CplexSolverError:
#raises this error when there is no solution
pass
#put pi and slack variables against the constraints
#TODO: clear up the name of self.n2c
if self.msg:
print("Cplex status=", lp.cplex_status)
lp.resolveOK = True
for var in lp.variables():
var.isModified = False
return lp.status
示例6: cplex_solution
# 需要導入模塊: import cplex [as 別名]
# 或者: from cplex import Cplex [as 別名]
def cplex_solution(self):
""" cplex solution """
# refactoring
rho = self.rho
n = self.n
q = self.q
my_obj = list(rho.reshape(1, n ** 2)[0]) + [0. for x in range(0, n)]
my_ub = [1 for x in range(0, n ** 2 + n)]
my_lb = [0 for x in range(0, n ** 2 + n)]
my_ctype = "".join(['I' for x in range(0, n ** 2 + n)])
my_rhs = [q] + [1 for x in range(0, n)] + \
[0 for x in range(0, n)] + [0.1 for x in range(0, n ** 2)]
my_sense = "".join(['E' for x in range(0, 1 + n)]) + \
"".join(['E' for x in range(0, n)]) + \
"".join(['L' for x in range(0, n ** 2)])
try:
my_prob = cplex.Cplex()
self._populate_by_row(my_prob, my_obj, my_ub, my_lb, my_ctype, my_sense, my_rhs)
my_prob.solve()
except Exception as ex: # pylint: disable=broad-except
print(str(ex))
return None, None
x = my_prob.solution.get_values()
x = np.array(x)
cost = my_prob.solution.get_objective_value()
return x, cost
示例7: createCplex
# 需要導入模塊: import cplex [as 別名]
# 或者: from cplex import Cplex [as 別名]
def createCplex( **params):
"""Create and return a :class:`cplex.Cplex` instance with disabled debugging output. Keyword
args are used to set parameters.
CPLEX parameters can be set by using their name in the python interface, excluding the
leading ``cplex.parameters.``, as key (e.g. ``workmem``, ``mip.strategy``).
"""
import cplex
cpx = cplex.Cplex()
stream = None
if params.get('debug', False):
stream = sys.stderr
if 'debug' in params:
del params['debug']
cpx.set_results_stream(stream)
cpx.set_warning_stream(stream)
cpx.set_error_stream(stream)
if 'version' in params:
assert cpx.get_version() == params.pop('version')
for arg, val in params.items():
parts = arg.split('.')
param = cpx.parameters
for part in parts:
param = getattr(param, part)
param.set(val)
return cpx
示例8: checkKeyboardInterrupt
# 需要導入模塊: import cplex [as 別名]
# 或者: from cplex import Cplex [as 別名]
def checkKeyboardInterrupt(cpx):
"""Checks the solution status of the given :class:`cplex.Cplex` instance for keyboard
interrupts, and raises a :class:`KeyboardInterrupt` exception in that case.
"""
import cplex
if cpx.solution.get_status() in (cplex._internal._constants.CPX_STAT_ABORT_USER,
cplex._internal._constants.CPXMIP_ABORT_FEAS,
cplex._internal._constants.CPXMIP_ABORT_INFEAS):
raise KeyboardInterrupt()
示例9: copy_cplex
# 需要導入模塊: import cplex [as 別名]
# 或者: from cplex import Cplex [as 別名]
def copy_cplex(cpx):
cpx_copy = Cplex(cpx)
cpx_parameters = cpx.parameters.get_changed()
for (pname, pvalue) in cpx_parameters:
phandle = reduce(getattr, str(pname).split("."), cpx_copy)
phandle.set(pvalue)
return cpx_copy
# Building
示例10: run_and_read_cplex
# 需要導入模塊: import cplex [as 別名]
# 或者: from cplex import Cplex [as 別名]
def run_and_read_cplex(n, problem_fn, solution_fn, solver_logfile,
solver_options, warmstart=None, store_basis=True):
"""
Solving function. Reads the linear problem file and passes it to the cplex
solver. If the solution is sucessful it returns variable solutions and
constraint dual values. Cplex must be installed for using this function
"""
if find_spec('cplex') is None:
raise ModuleNotFoundError("Optional dependency 'cplex' not found."
"Install via 'conda install -c ibmdecisionoptimization cplex' "
"or 'pip install cplex'")
import cplex
m = cplex.Cplex()
out = m.set_log_stream(solver_logfile)
if solver_options is not None:
for key, value in solver_options.items():
param = m.parameters
for key_layer in key.split("."):
param = getattr(param, key_layer)
param.set(value)
m.read(problem_fn)
if warmstart:
m.start.read_basis(warmstart)
m.solve()
is_lp = m.problem_type[m.get_problem_type()] == 'LP'
termination_condition = m.solution.get_status_string()
if 'optimal' in termination_condition:
status = 'ok'
termination_condition = 'optimal'
else:
status = 'warning'
if (status == 'ok') and store_basis and is_lp:
n.basis_fn = solution_fn.replace('.sol', '.bas')
try:
m.solution.basis.write(n.basis_fn)
except cplex.exceptions.errors.CplexSolverError:
logger.info('No model basis stored')
del n.basis_fn
objective = m.solution.get_objective_value()
variables_sol = pd.Series(m.solution.get_values(), m.variables.get_names())\
.pipe(set_int_index)
if is_lp:
constraints_dual = pd.Series(m.solution.get_dual_values(),
m.linear_constraints.get_names()).pipe(set_int_index)
else:
logger.warning("Shadow prices of MILP couldn't be parsed")
constraints_dual = pd.Series(index=m.linear_constraints.get_names())\
.pipe(set_int_index)
del m
return (status, termination_condition, variables_sol, constraints_dual,
objective)
示例11: findSolutionValues
# 需要導入模塊: import cplex [as 別名]
# 或者: from cplex import Cplex [as 別名]
def findSolutionValues(self, lp):
CplexLpStatus = {lp.solverModel.solution.status.MIP_optimal: LpStatusOptimal,
lp.solverModel.solution.status.optimal: LpStatusOptimal,
lp.solverModel.solution.status.optimal_tolerance: LpStatusOptimal,
lp.solverModel.solution.status.infeasible: LpStatusInfeasible,
lp.solverModel.solution.status.infeasible_or_unbounded: LpStatusInfeasible,
lp.solverModel.solution.status.MIP_infeasible: LpStatusInfeasible,
lp.solverModel.solution.status.MIP_infeasible_or_unbounded: LpStatusInfeasible,
lp.solverModel.solution.status.unbounded: LpStatusUnbounded,
lp.solverModel.solution.status.MIP_unbounded: LpStatusUnbounded,
lp.solverModel.solution.status.abort_dual_obj_limit: LpStatusNotSolved,
lp.solverModel.solution.status.abort_iteration_limit: LpStatusNotSolved,
lp.solverModel.solution.status.abort_obj_limit: LpStatusNotSolved,
lp.solverModel.solution.status.abort_relaxed: LpStatusNotSolved,
lp.solverModel.solution.status.abort_time_limit: LpStatusNotSolved,
lp.solverModel.solution.status.abort_user: LpStatusNotSolved}
lp.cplex_status = lp.solverModel.solution.get_status()
lp.status = CplexLpStatus.get(lp.cplex_status, LpStatusUndefined)
var_names = [var.name for var in lp.variables()]
con_names = [con for con in lp.constraints]
try:
objectiveValue = lp.solverModel.solution.get_objective_value()
variablevalues = dict(zip(var_names, lp.solverModel.solution.get_values(var_names)))
lp.assignVarsVals(variablevalues)
constraintslackvalues = dict(zip(con_names, lp.solverModel.solution.get_linear_slacks(con_names)))
lp.assignConsSlack(constraintslackvalues)
if lp.solverModel.get_problem_type == cplex.Cplex.problem_type.LP:
variabledjvalues = dict(zip(var_names, lp.solverModel.solution.get_reduced_costs(var_names)))
lp.assignVarsDj(variabledjvalues)
constraintpivalues = dict(zip(con_names, lp.solverModel.solution.get_dual_values(con_names)))
lp.assignConsPi(constraintpivalues)
except cplex.exceptions.CplexSolverError:
#raises this error when there is no solution
pass
#put pi and slack variables against the constraints
#TODO: clear up the name of self.n2c
if self.msg:
print("Cplex status=", lp.cplex_status)
lp.resolveOK = True
for var in lp.variables():
var.isModified = False
return lp.status