/* -*- mode: C++; indent-tabs-mode: nil; -*-
* This file is a part of LEMON, a generic C++ optimization library.
* Copyright (C) 2003-2009
* Egervary Jeno Kombinatorikus Optimalizalasi Kutatocsoport
* (Egervary Research Group on Combinatorial Optimization, EGRES).
* Permission to use, modify and distribute this software is granted
* provided that this copyright notice appears in all copies. For
* precise terms see the accompanying LICENSE file.
* This software is provided "AS IS" with no warranty of any kind,
* express or implied, and with no claim as to its suitability for any
#include <ilcplex/cplex.h>
///\brief Implementation of the LEMON-CPLEX lp solver interface.
CplexEnv::LicenseError::LicenseError(int status) {
if (!CPXgeterrorstring(0, status, _message)) {
std::strcpy(_message, "Cplex unknown error");
_env = CPXopenCPLEX(&status);
throw LicenseError(status);
CplexEnv::CplexEnv(const CplexEnv& other) {
CplexEnv& CplexEnv::operator=(const CplexEnv& other) {
CplexBase::CplexBase() : LpBase() {
_prob = CPXcreateprob(cplexEnv(), &status, "Cplex problem");
messageLevel(MESSAGE_NOTHING);
CplexBase::CplexBase(const CplexEnv& env)
_prob = CPXcreateprob(cplexEnv(), &status, "Cplex problem");
messageLevel(MESSAGE_NOTHING);
CplexBase::CplexBase(const CplexBase& cplex)
_prob = CPXcloneprob(cplexEnv(), cplex._prob, &status);
messageLevel(MESSAGE_NOTHING);
CplexBase::~CplexBase() {
CPXfreeprob(cplexEnv(),&_prob);
int CplexBase::_addCol() {
int i = CPXgetnumcols(cplexEnv(), _prob);
double lb = -INF, ub = INF;
CPXnewcols(cplexEnv(), _prob, 1, 0, &lb, &ub, 0, 0);
int CplexBase::_addRow() {
int i = CPXgetnumrows(cplexEnv(), _prob);
CPXnewrows(cplexEnv(), _prob, 1, &ub, &s, 0, 0);
void CplexBase::_eraseCol(int i) {
CPXdelcols(cplexEnv(), _prob, i, i);
void CplexBase::_eraseRow(int i) {
CPXdelrows(cplexEnv(), _prob, i, i);
void CplexBase::_eraseColId(int i) {
void CplexBase::_eraseRowId(int i) {
void CplexBase::_getColName(int col, std::string &name) const {
CPXgetcolname(cplexEnv(), _prob, 0, 0, 0, &size, col, col);
std::vector<char> buf(size);
CPXgetcolname(cplexEnv(), _prob, &cname, &buf.front(), size,
void CplexBase::_setColName(int col, const std::string &name) {
cname = const_cast<char*>(name.c_str());
CPXchgcolname(cplexEnv(), _prob, 1, &col, &cname);
int CplexBase::_colByName(const std::string& name) const {
if (CPXgetcolindex(cplexEnv(), _prob,
const_cast<char*>(name.c_str()), &index) == 0) {
void CplexBase::_getRowName(int row, std::string &name) const {
CPXgetrowname(cplexEnv(), _prob, 0, 0, 0, &size, row, row);
std::vector<char> buf(size);
CPXgetrowname(cplexEnv(), _prob, &cname, &buf.front(), size,
void CplexBase::_setRowName(int row, const std::string &name) {
cname = const_cast<char*>(name.c_str());
CPXchgrowname(cplexEnv(), _prob, 1, &row, &cname);
int CplexBase::_rowByName(const std::string& name) const {
if (CPXgetrowindex(cplexEnv(), _prob,
const_cast<char*>(name.c_str()), &index) == 0) {
void CplexBase::_setRowCoeffs(int i, ExprIterator b,
std::vector<int> indices;
std::vector<int> rowlist;
std::vector<Value> values;
for(ExprIterator it=b; it!=e; ++it) {
indices.push_back(it->first);
values.push_back(it->second);
CPXchgcoeflist(cplexEnv(), _prob, values.size(),
&rowlist.front(), &indices.front(), &values.front());
void CplexBase::_getRowCoeffs(int i, InsertIterator b) const {
int tmp1, tmp2, tmp3, length;
CPXgetrows(cplexEnv(), _prob, &tmp1, &tmp2, 0, 0, 0, &length, i, i);
std::vector<int> indices(length);
std::vector<double> values(length);
CPXgetrows(cplexEnv(), _prob, &tmp1, &tmp2,
&indices.front(), &values.front(),
for (int i = 0; i < length; ++i) {
*b = std::make_pair(indices[i], values[i]);
void CplexBase::_setColCoeffs(int i, ExprIterator b, ExprIterator e) {
std::vector<int> indices;
std::vector<int> collist;
std::vector<Value> values;
for(ExprIterator it=b; it!=e; ++it) {
indices.push_back(it->first);
values.push_back(it->second);
CPXchgcoeflist(cplexEnv(), _prob, values.size(),
&indices.front(), &collist.front(), &values.front());
void CplexBase::_getColCoeffs(int i, InsertIterator b) const {
int tmp1, tmp2, tmp3, length;
CPXgetcols(cplexEnv(), _prob, &tmp1, &tmp2, 0, 0, 0, &length, i, i);
std::vector<int> indices(length);
std::vector<double> values(length);
CPXgetcols(cplexEnv(), _prob, &tmp1, &tmp2,
&indices.front(), &values.front(),
for (int i = 0; i < length; ++i) {
*b = std::make_pair(indices[i], values[i]);
void CplexBase::_setCoeff(int row, int col, Value value) {
CPXchgcoef(cplexEnv(), _prob, row, col, value);
CplexBase::Value CplexBase::_getCoeff(int row, int col) const {
CPXgetcoef(cplexEnv(), _prob, row, col, &value);
void CplexBase::_setColLowerBound(int i, Value value) {
CPXchgbds(cplexEnv(), _prob, 1, &i, &s, &value);
CplexBase::Value CplexBase::_getColLowerBound(int i) const {
CPXgetlb(cplexEnv(), _prob, &res, i, i);
return res <= -CPX_INFBOUND ? -INF : res;
void CplexBase::_setColUpperBound(int i, Value value)
CPXchgbds(cplexEnv(), _prob, 1, &i, &s, &value);
CplexBase::Value CplexBase::_getColUpperBound(int i) const {
CPXgetub(cplexEnv(), _prob, &res, i, i);
return res >= CPX_INFBOUND ? INF : res;
CplexBase::Value CplexBase::_getRowLowerBound(int i) const {
CPXgetsense(cplexEnv(), _prob, &s, i, i);
CPXgetrhs(cplexEnv(), _prob, &res, i, i);
return res <= -CPX_INFBOUND ? -INF : res;
CplexBase::Value CplexBase::_getRowUpperBound(int i) const {
CPXgetsense(cplexEnv(), _prob, &s, i, i);
CPXgetrhs(cplexEnv(), _prob, &res, i, i);
return res >= CPX_INFBOUND ? INF : res;
CPXgetrhs(cplexEnv(), _prob, &res, i, i);
CPXgetrngval(cplexEnv(), _prob, &rng, i, i);
return res >= CPX_INFBOUND ? INF : res;
//This is easier to implement
void CplexBase::_set_row_bounds(int i, Value lb, Value ub) {
CPXchgsense(cplexEnv(), _prob, 1, &i, &s);
CPXchgrhs(cplexEnv(), _prob, 1, &i, &ub);
CPXchgsense(cplexEnv(), _prob, 1, &i, &s);
CPXchgrhs(cplexEnv(), _prob, 1, &i, &lb);
CPXchgsense(cplexEnv(), _prob, 1, &i, &s);
CPXchgrhs(cplexEnv(), _prob, 1, &i, &lb);
CPXchgsense(cplexEnv(), _prob, 1, &i, &s);
CPXchgrhs(cplexEnv(), _prob, 1, &i, &lb);
CPXchgrngval(cplexEnv(), _prob, 1, &i, &len);
void CplexBase::_setRowLowerBound(int i, Value lb)
LEMON_ASSERT(lb != INF, "Invalid bound");
_set_row_bounds(i, lb, CplexBase::_getRowUpperBound(i));
void CplexBase::_setRowUpperBound(int i, Value ub)
LEMON_ASSERT(ub != -INF, "Invalid bound");
_set_row_bounds(i, CplexBase::_getRowLowerBound(i), ub);
void CplexBase::_setObjCoeffs(ExprIterator b, ExprIterator e)
std::vector<int> indices;
std::vector<Value> values;
for(ExprIterator it=b; it!=e; ++it) {
indices.push_back(it->first);
values.push_back(it->second);
CPXchgobj(cplexEnv(), _prob, values.size(),
&indices.front(), &values.front());
void CplexBase::_getObjCoeffs(InsertIterator b) const
int num = CPXgetnumcols(cplexEnv(), _prob);
std::vector<Value> x(num);
CPXgetobj(cplexEnv(), _prob, &x.front(), 0, num - 1);
for (int i = 0; i < num; ++i) {
*b = std::make_pair(i, x[i]);
void CplexBase::_setObjCoeff(int i, Value obj_coef)
CPXchgobj(cplexEnv(), _prob, 1, &i, &obj_coef);
CplexBase::Value CplexBase::_getObjCoeff(int i) const
CPXgetobj(cplexEnv(), _prob, &x, i, i);
void CplexBase::_setSense(CplexBase::Sense sense) {
CPXchgobjsen(cplexEnv(), _prob, CPX_MIN);
CPXchgobjsen(cplexEnv(), _prob, CPX_MAX);
CplexBase::Sense CplexBase::_getSense() const {
switch (CPXgetobjsen(cplexEnv(), _prob)) {
LEMON_ASSERT(false, "Invalid sense");
return CplexBase::Sense();
void CplexBase::_clear() {
CPXfreeprob(cplexEnv(),&_prob);
_prob = CPXcreateprob(cplexEnv(), &status, "Cplex problem");
void CplexBase::_messageLevel(MessageLevel level) {
_message_enabled = false;
void CplexBase::_applyMessageLevel() {
CPXsetintparam(cplexEnv(), CPX_PARAM_SCRIND,
_message_enabled ? CPX_ON : CPX_OFF);
: LpBase(), LpSolver(), CplexBase() {}
CplexLp::CplexLp(const CplexEnv& env)
: LpBase(), LpSolver(), CplexBase(env) {}
CplexLp::CplexLp(const CplexLp& other)
: LpBase(), LpSolver(), CplexBase(other) {}
CplexLp* CplexLp::newSolver() const { return new CplexLp; }
CplexLp* CplexLp::cloneSolver() const {return new CplexLp(*this); }
const char* CplexLp::_solverName() const { return "CplexLp"; }
void CplexLp::_clear_temporals() {
// The routine returns zero unless an error occurred during the
// optimization. Examples of errors include exhausting available
// memory (CPXERR_NO_MEMORY) or encountering invalid data in the
// CPLEX problem object (CPXERR_NO_PROBLEM). Exceeding a
// user-specified CPLEX limit, or proving the model infeasible or
// unbounded, are not considered errors. Note that a zero return
// value does not necessarily mean that a solution exists. Use query
// routines CPXsolninfo, CPXgetstat, and CPXsolution to obtain
// further information about the status of the optimization.
CplexLp::SolveExitStatus CplexLp::convertStatus(int status) {
switch (CPXgetstat(cplexEnv(), _prob)) {
case CPX_STAT_INFEASIBLE:
//We want to exclude some cases
switch (CPXgetstat(cplexEnv(), _prob)) {
case CPX_TIME_LIM_INFEAS:
CplexLp::SolveExitStatus CplexLp::_solve() {
return convertStatus(CPXlpopt(cplexEnv(), _prob));
CplexLp::SolveExitStatus CplexLp::solvePrimal() {
return convertStatus(CPXprimopt(cplexEnv(), _prob));
CplexLp::SolveExitStatus CplexLp::solveDual() {
return convertStatus(CPXdualopt(cplexEnv(), _prob));
CplexLp::SolveExitStatus CplexLp::solveBarrier() {
return convertStatus(CPXbaropt(cplexEnv(), _prob));
CplexLp::Value CplexLp::_getPrimal(int i) const {
CPXgetx(cplexEnv(), _prob, &x, i, i);
CplexLp::Value CplexLp::_getDual(int i) const {
CPXgetpi(cplexEnv(), _prob, &y, i, i);
CplexLp::Value CplexLp::_getPrimalValue() const {
CPXgetobjval(cplexEnv(), _prob, &objval);
CplexLp::VarStatus CplexLp::_getColStatus(int i) const {
if (_col_status.empty()) {
_col_status.resize(CPXgetnumcols(cplexEnv(), _prob));
CPXgetbase(cplexEnv(), _prob, &_col_status.front(), 0);
switch (_col_status[i]) {
LEMON_ASSERT(false, "Wrong column status");
return CplexLp::VarStatus();
CplexLp::VarStatus CplexLp::_getRowStatus(int i) const {
if (_row_status.empty()) {
_row_status.resize(CPXgetnumrows(cplexEnv(), _prob));
CPXgetbase(cplexEnv(), _prob, 0, &_row_status.front());
switch (_row_status[i]) {
CPXgetsense(cplexEnv(), _prob, &s, i, i);
return s != 'L' ? LOWER : UPPER;
LEMON_ASSERT(false, "Wrong row status");
return CplexLp::VarStatus();
CplexLp::Value CplexLp::_getPrimalRay(int i) const {
if (_primal_ray.empty()) {
_primal_ray.resize(CPXgetnumcols(cplexEnv(), _prob));
CPXgetray(cplexEnv(), _prob, &_primal_ray.front());
CplexLp::Value CplexLp::_getDualRay(int i) const {
// Cplex 7.0 status values
// This table lists the statuses, returned by the CPXgetstat()
// routine, for solutions to LP problems or mixed integer problems. If
// no solution exists, the return value is zero.
// Optimal solution found
// Objective limit exceeded in Phase II
// Iteration limit exceeded in Phase II
// Iteration limit exceeded in Phase I
// Time limit exceeded in Phase II
// Time limit exceeded in Phase I
// Problem non-optimal, singularities in Phase II
// 10 CPX_NUM_BEST_INFEAS
// Problem non-optimal, singularities in Phase I
// Optimal solution found, unscaled infeasibilities
// 14 CPX_ABORT_DUAL_INFEAS
// Aborted in barrier, dual infeasible
// 15 CPX_ABORT_PRIM_INFEAS
// Aborted in barrier, primal infeasible
// 16 CPX_ABORT_PRIM_DUAL_INFEAS
// Aborted in barrier, primal and dual infeasible
// 17 CPX_ABORT_PRIM_DUAL_FEAS
// Aborted in barrier, primal and dual feasible
// 18 CPX_ABORT_CROSSOVER
// Infeasible or unbounded
// ??case CPX_ABORT_DUAL_INFEAS
// ??case CPX_ABORT_CROSSOVER
//Some more interesting stuff:
// CPX_PARAM_PROBMETHOD 1062 int LPMETHOD
// Description: Method for linear optimization.
// Determines which algorithm is used when CPXlpopt() (or "optimize"
// in the Interactive Optimizer) is called. Currently the behavior of
// the "Automatic" setting is that CPLEX simply invokes the dual
// simplex method, but this capability may be expanded in the future
// so that CPLEX chooses the method based on problem characteristics
void statusSwitch(CPXENVptr cplexEnv(),int& stat){
CPXgetintparam (cplexEnv(),CPX_PARAM_PROBMETHOD,&lpmethod);
if (stat==CPX_UNBOUNDED){
if (stat==CPX_INFEASIBLE)
void statusSwitch(CPXENVptr,int&){}
CplexLp::ProblemType CplexLp::_getPrimalType() const {
// Unboundedness not treated well: the following is from cplex 9.0 doc
// The treatment of models that are unbounded involves a few
// subtleties. Specifically, a declaration of unboundedness means that
// ILOG CPLEX has determined that the model has an unbounded
// ray. Given any feasible solution x with objective z, a multiple of
// the unbounded ray can be added to x to give a feasible solution
// with objective z-1 (or z+1 for maximization models). Thus, if a
// feasible solution exists, then the optimal objective is
// unbounded. Note that ILOG CPLEX has not necessarily concluded that
// a feasible solution exists. Users can call the routine CPXsolninfo
// to determine whether ILOG CPLEX has also concluded that the model
// has a feasible solution.
int stat = CPXgetstat(cplexEnv(), _prob);
case CPX_STAT_INFEASIBLE:
statusSwitch(cplexEnv(),stat);
//CPXgetstat(cplexEnv(), _prob);
return UNDEFINED; //Undefined
case CPX_OPTIMAL:
//Optimal
case CPX_UNBOUNDED:
//Unbounded
return INFEASIBLE;//In case of dual simplex
case CPX_INFEASIBLE:
//Infeasible
// case CPX_IT_LIM_INFEAS:
// case CPX_TIME_LIM_INFEAS:
// case CPX_NUM_BEST_INFEAS:
// case CPX_OPTIMAL_INFEAS:
// case CPX_ABORT_INFEAS:
// case CPX_ABORT_PRIM_INFEAS:
// case CPX_ABORT_PRIM_DUAL_INFEAS:
return UNBOUNDED;//In case of dual simplex
// case CPX_TIME_LIM_FEAS:
// case CPX_NUM_BEST_FEAS:
// case CPX_ABORT_PRIM_DUAL_FEAS:
return UNDEFINED; //Everything else comes here
// Cplex 9.0 status values
// CPX_STAT_ABORT_DUAL_OBJ_LIM
// CPX_STAT_ABORT_OBJ_LIM
// CPX_STAT_ABORT_PRIM_OBJ_LIM
// CPX_STAT_ABORT_TIME_LIM
// CPX_STAT_FEASIBLE_RELAXED
// CPX_STAT_OPTIMAL_FACE_UNBOUNDED
// CPX_STAT_OPTIMAL_INFEAS
// CPX_STAT_OPTIMAL_RELAXED
CplexLp::ProblemType CplexLp::_getDualType() const {
int stat = CPXgetstat(cplexEnv(), _prob);
statusSwitch(cplexEnv(),stat);
return UNDEFINED; //Undefined
case CPX_OPTIMAL:
//Optimal
return UNDEFINED; //Everything else comes here
: LpBase(), MipSolver(), CplexBase() {
CPXchgprobtype(cplexEnv(), _prob, CPXPROB_MIP);
CPXchgprobtype(cplexEnv(), _prob, CPXPROB_MILP);
CplexMip::CplexMip(const CplexEnv& env)
: LpBase(), MipSolver(), CplexBase(env) {
CPXchgprobtype(cplexEnv(), _prob, CPXPROB_MIP);
CPXchgprobtype(cplexEnv(), _prob, CPXPROB_MILP);
CplexMip::CplexMip(const CplexMip& other)
: LpBase(), MipSolver(), CplexBase(other) {}
CplexMip* CplexMip::newSolver() const { return new CplexMip; }
CplexMip* CplexMip::cloneSolver() const {return new CplexMip(*this); }
const char* CplexMip::_solverName() const { return "CplexMip"; }
void CplexMip::_setColType(int i, CplexMip::ColTypes col_type) {
// Note If a variable is to be changed to binary, a call to CPXchgbds
// should also be made to change the bounds to 0 and 1.
CPXchgctype (cplexEnv(), _prob, 1, &i, &t);
CPXchgctype (cplexEnv(), _prob, 1, &i, &t);
CplexMip::ColTypes CplexMip::_getColType(int i) const {
CPXgetctype (cplexEnv(), _prob, &t, i, i);
LEMON_ASSERT(false, "Invalid column type");
CplexMip::SolveExitStatus CplexMip::_solve() {
status = CPXmipopt (cplexEnv(), _prob);
CplexMip::ProblemType CplexMip::_getType() const {
int stat = CPXgetstat(cplexEnv(), _prob);
//Fortunately, MIP statuses did not change for cplex 8.0
// Optimal integer solution has been found.
// Optimal soluton with the tolerance defined by epgap or epagap has
//This also exists in later issues
// case CPXMIP_UNBOUNDED:
//Unboundedness not treated well: the following is from cplex 9.0 doc
// The treatment of models that are unbounded involves a few
// subtleties. Specifically, a declaration of unboundedness means that
// ILOG CPLEX has determined that the model has an unbounded
// ray. Given any feasible solution x with objective z, a multiple of
// the unbounded ray can be added to x to give a feasible solution
// with objective z-1 (or z+1 for maximization models). Thus, if a
// feasible solution exists, then the optimal objective is
// unbounded. Note that ILOG CPLEX has not necessarily concluded that
// a feasible solution exists. Users can call the routine CPXsolninfo
// to determine whether ILOG CPLEX has also concluded that the model
// has a feasible solution.
CplexMip::Value CplexMip::_getSol(int i) const {
CPXgetmipx(cplexEnv(), _prob, &x, i, i);
CplexMip::Value CplexMip::_getSolValue() const {
CPXgetmipobjval(cplexEnv(), _prob, &objval);