Google OR-Tools v9.9
a fast and portable software suite for combinatorial optimization
Loading...
Searching...
No Matches
operations_research::CplexInterface Class Reference
Inheritance diagram for operations_research::CplexInterface:
operations_research::MPSolverInterface

Public Member Functions

 CplexInterface (MPSolver *const solver, bool mip)
 Creates a LP/MIP instance.
 
 ~CplexInterface ()
 
virtual void SetOptimizationDirection (bool maximize)
 Sets the optimization direction (min/max).
 
virtual MPSolver::ResultStatus Solve (MPSolverParameters const &param)
 
virtual void Reset ()
 ---— Model modifications and extraction --—
 
virtual void SetVariableBounds (int var_index, double lb, double ub)
 Modifies bounds of an extracted variable.
 
virtual void SetVariableInteger (int var_index, bool integer)
 Modifies integrality of an extracted variable.
 
virtual void SetConstraintBounds (int row_index, double lb, double ub)
 Modify bounds of an extracted variable.
 
virtual void AddRowConstraint (MPConstraint *const ct)
 Adds a linear constraint.
 
virtual void AddVariable (MPVariable *const var)
 Add a variable.
 
virtual void SetCoefficient (MPConstraint *const constraint, MPVariable const *const variable, double new_value, double old_value)
 Changes a coefficient in a constraint.
 
virtual void ClearConstraint (MPConstraint *const constraint)
 Clear a constraint from all its terms.
 
virtual void SetObjectiveCoefficient (MPVariable const *const variable, double coefficient)
 Change a coefficient in the linear objective.
 
virtual void SetObjectiveOffset (double value)
 Change the constant term in the linear objective.
 
virtual void ClearObjective ()
 Clear the objective from all its terms.
 
virtual int64_t iterations () const
 ---— Query statistics on the solution and the solve ---—
 
virtual int64_t nodes () const
 Number of branch-and-bound nodes. Only available for discrete problems.
 
virtual MPSolver::BasisStatus row_status (int constraint_index) const
 Returns the basis status of a row.
 
virtual MPSolver::BasisStatus column_status (int variable_index) const
 Returns the basis status of a column.
 
virtual bool IsContinuous () const
 --— Misc --—
 
virtual bool IsLP () const
 Returns true if the problem is continuous and linear.
 
virtual bool IsMIP () const
 Returns true if the problem is discrete and linear.
 
bool SetSolverSpecificParametersAsString (const std::string &parameters) override
 
virtual void ExtractNewVariables ()
 Extract all variables that have not yet been extracted.
 
virtual void ExtractNewConstraints ()
 Extract constraints that have not yet been extracted.
 
virtual void ExtractObjective ()
 Extract the objective function.
 
virtual std::string SolverVersion () const
 Returns a string describing the underlying solver and its version.
 
virtual void * underlying_solver ()
 Returns the underlying solver.
 
virtual double ComputeExactConditionNumber () const
 
- Public Member Functions inherited from operations_research::MPSolverInterface
 MPSolverInterface (MPSolver *solver)
 
virtual ~MPSolverInterface ()
 
virtual std::optional< MPSolutionResponse > DirectlySolveProto (const MPModelRequest &, std::atomic< bool > *)
 
virtual void Write (const std::string &filename)
 
virtual bool AddIndicatorConstraint (MPConstraint *const)
 
virtual void BranchingPriorityChangedForVariable (int)
 
double best_objective_bound () const
 
double objective_value () const
 Returns the objective value of the best solution found so far.
 
bool CheckSolutionIsSynchronized () const
 
virtual bool CheckSolutionExists () const
 
bool CheckSolutionIsSynchronizedAndExists () const
 Handy shortcut to do both checks above (it is often used).
 
int last_variable_index () const
 Returns the index of the last variable extracted.
 
bool variable_is_extracted (int var_index) const
 
void set_variable_as_extracted (int var_index, bool extracted)
 
bool constraint_is_extracted (int ct_index) const
 
void set_constraint_as_extracted (int ct_index, bool extracted)
 
bool quiet () const
 Returns the boolean indicating the verbosity of the solver output.
 
void set_quiet (bool quiet_value)
 Sets the boolean indicating the verbosity of the solver output.
 
MPSolver::ResultStatus result_status () const
 Returns the result status of the last solve.
 
virtual void SetStartingLpBasis (const std::vector< MPSolver::BasisStatus > &, const std::vector< MPSolver::BasisStatus > &)
 See MPSolver::SetStartingLpBasis().
 
virtual double infinity ()
 
virtual bool InterruptSolve ()
 
virtual bool NextSolution ()
 See MPSolver::NextSolution() for contract.
 
virtual void SetCallback (MPCallback *)
 See MPSolver::SetCallback() for details.
 
virtual bool SupportsCallbacks () const
 

Protected Member Functions

virtual void SetParameters (MPSolverParameters const &param)
 Set all parameters in the underlying solver.
 
virtual void SetRelativeMipGap (double value)
 Set each parameter in the underlying solver.
 
virtual void SetPrimalTolerance (double value)
 
virtual void SetDualTolerance (double value)
 
virtual void SetPresolveMode (int value)
 
virtual void SetScalingMode (int value)
 Sets the scaling mode.
 
virtual void SetLpAlgorithm (int value)
 
virtual bool ReadParameterFile (std::string const &filename)
 
virtual std::string ValidFileExtensionForParameterFile () const
 
- Protected Member Functions inherited from operations_research::MPSolverInterface
void ExtractModel ()
 Extracts model stored in MPSolver.
 
void ResetExtractionInformation ()
 Resets the extraction information.
 
void InvalidateSolutionSynchronization ()
 
void SetCommonParameters (const MPSolverParameters &param)
 Sets parameters common to LP and MIP in the underlying solver.
 
void SetMIPParameters (const MPSolverParameters &param)
 Sets MIP specific parameters in the underlying solver.
 
void SetUnsupportedDoubleParam (MPSolverParameters::DoubleParam param)
 Sets an unsupported double parameter.
 
virtual void SetUnsupportedIntegerParam (MPSolverParameters::IntegerParam param)
 Sets an unsupported integer parameter.
 
void SetDoubleParamToUnsupportedValue (MPSolverParameters::DoubleParam param, double value)
 Sets a supported double parameter to an unsupported value.
 
virtual void SetIntegerParamToUnsupportedValue (MPSolverParameters::IntegerParam param, int value)
 Sets a supported integer parameter to an unsupported value.
 
virtual absl::Status SetNumThreads (int num_threads)
 Sets the number of threads to be used by the solver.
 

Additional Inherited Members

- Public Types inherited from operations_research::MPSolverInterface
enum  SynchronizationStatus { MUST_RELOAD , MODEL_SYNCHRONIZED , SOLUTION_SYNCHRONIZED }
 
- Static Public Attributes inherited from operations_research::MPSolverInterface
static constexpr int64_t kUnknownNumberOfIterations = -1
 
static constexpr int64_t kUnknownNumberOfNodes = -1
 
- Protected Attributes inherited from operations_research::MPSolverInterface
MPSolver *const solver_
 
SynchronizationStatus sync_status_
 Indicates whether the model and the solution are synchronized.
 
MPSolver::ResultStatus result_status_
 
bool maximize_
 Optimization direction.
 
int last_constraint_index_
 Index in MPSolver::variables_ of last constraint extracted.
 
int last_variable_index_
 Index in MPSolver::constraints_ of last variable extracted.
 
double objective_value_
 The value of the objective function.
 
double best_objective_bound_
 The value of the best objective bound. Used only for MIP solvers.
 
bool quiet_
 Boolean indicator for the verbosity of the solver output.
 
- Static Protected Attributes inherited from operations_research::MPSolverInterface
static const int kDummyVariableIndex = 0
 -------— MPSolverInterface -------—
 

Detailed Description

For a model that is extracted to an instance of this class there is a 1:1 corresponence between MPVariable instances and CPLEX columns: the index of an extracted variable is the column index in the CPLEX model. Similiar for instances of MPConstraint: the index of the constraint in the model is the row index in the CPLEX model.

Definition at line 59 of file cplex_interface.cc.

Constructor & Destructor Documentation

◆ CplexInterface()

operations_research::CplexInterface::CplexInterface ( MPSolver *const solver,
bool mip )
explicit

Creates a LP/MIP instance.

Note
'mip' specifies the type of the problem (either continuous or mixed integer. This type is fixed for the lifetime of the instance. There are no dynamic changes to the model type.

Definition at line 216 of file cplex_interface.cc.

◆ ~CplexInterface()

operations_research::CplexInterface::~CplexInterface ( )

Definition at line 241 of file cplex_interface.cc.

Member Function Documentation

◆ AddRowConstraint()

void operations_research::CplexInterface::AddRowConstraint ( MPConstraint *const ct)
virtual

Adds a linear constraint.

This is currently only invoked when a new constraint is created, see MPSolver::MakeRowConstraint(). At this point we only have the lower and upper bounds of the constraint. We could immediately call CPXXaddrows() here but it is usually much faster to handle the fully populated constraint in ExtractNewConstraints() right before the solve.

Implements operations_research::MPSolverInterface.

Definition at line 446 of file cplex_interface.cc.

◆ AddVariable()

void operations_research::CplexInterface::AddVariable ( MPVariable *const var)
virtual

Add a variable.

This is currently only invoked when a new variable is created, see MPSolver::MakeVar(). At this point the variable does not appear in any constraints or the objective function. We could invoke CPXXaddcols() to immediately create the variable here but it is usually much faster to handle the fully setup variable in ExtractNewVariables() right before the solve.

Implements operations_research::MPSolverInterface.

Definition at line 456 of file cplex_interface.cc.

◆ ClearConstraint()

void operations_research::CplexInterface::ClearConstraint ( MPConstraint *const constraint)
virtual

Clear a constraint from all its terms.

There is nothing to do if the constraint was not even extracted.

Clearing a constraint means setting all coefficients in the corresponding row to 0 (we cannot just delete the row since that would renumber all the constraints/rows after it). Modifying coefficients in the matrix is potentially pretty expensive since they must be found in the sparse matrix representation. That is why by default we do not modify the coefficients here but only mark the low-level modeling object "out of sync".

Implements operations_research::MPSolverInterface.

Definition at line 497 of file cplex_interface.cc.

◆ ClearObjective()

void operations_research::CplexInterface::ClearObjective ( )
virtual

Clear the objective from all its terms.

Since the objective function is stored as a dense vector updating it is O(n), so we usually perform the update immediately. If we want to support incremental extraction then we have no choice but to perform the update immediately.

We only need to reset variables that have been extracted.

Implements operations_research::MPSolverInterface.

Definition at line 565 of file cplex_interface.cc.

◆ column_status()

MPSolver::BasisStatus operations_research::CplexInterface::column_status ( int variable_index) const
virtual

Returns the basis status of a column.

Implements operations_research::MPSolverInterface.

Definition at line 659 of file cplex_interface.cc.

◆ ComputeExactConditionNumber()

virtual double operations_research::CplexInterface::ComputeExactConditionNumber ( ) const
inlinevirtual

Computes exact condition number. Only available for continuous problems and only implemented in GLPK.

Override this method in interfaces that actually support it.

Reimplemented from operations_research::MPSolverInterface.

Definition at line 128 of file cplex_interface.cc.

◆ ExtractNewConstraints()

void operations_research::CplexInterface::ExtractNewConstraints ( )
virtual

Extract constraints that have not yet been extracted.

Note
The code assumes that a linear expression can never contain non-zero duplicates.

Without incremental extraction ExtractModel() is always called to extract the full model.

There are constraints that are not yet extracted.

Update indices of new constraints before actually extracting them. In case of error we will just reset the indices.

Loop over the new constraints, collecting rows for up to CHUNK constraints into the arrays so that adding constraints is faster.

Collect up to CHUNK constraints into the arrays.

Stop if there is not enough room in the arrays to add the current constraint.

Setup right-hand side of constraint.

Setup left-hand side of constraint.

Finally the name of the constraint.

Undo all changes in case of error.

Implements operations_research::MPSolverInterface.

Definition at line 845 of file cplex_interface.cc.

◆ ExtractNewVariables()

void operations_research::CplexInterface::ExtractNewVariables ( )
virtual

Extract all variables that have not yet been extracted.

Note
The code assumes that a linear expression can never contain non-zero duplicates.

Without incremental extraction ExtractModel() is always called to extract the full model.

There are non-extracted variables. Extract them now.

Arrays for modifying the problem are setup. Update the index of variables that will get extracted now. Updating indices before the actual extraction makes things much simpler in case we support incremental extraction. In case of error we just reset the indeces.

If we support incremental extraction then we must update existing constraints with the new variables. To do that we use CPXXaddcols() to actually create the variables. This is supposed to be faster than combining CPXXnewcols() and CPXXchgcoeflist().

For each column count the size of the intersection with existing constraints.

Todo
: Use a bitarray to flag the constraints that actually intersect new variables?

At least one of the new variables did intersect with an old constraint. We have to create the new columns via CPXXaddcols().

Here is how cmatbeg[] is setup:

  • it is initialized as [ 0, 0, collen[0], collen[0]+collen[1], ... ] so that cmatbeg[j+1] tells us where in cmatind[] and cmatval[] we need to put the next nonzero for column j
  • after nonzeros have been setup the array looks like [ 0, collen[0], collen[0]+collen[1], ... ] so that it is the correct input argument for CPXXaddcols

Either incremental extraction is not supported or none of the new variables did intersect an existing constraint. We can just use CPXXnewcols() to create the new variables.

Incremental extraction: we must update the ctype of the newly created variables (CPXXaddcols() does not allow specifying the ctype)

Query the actual number of columns in case we did not manage to extract all columns.

Undo all changes in case of error.

Implements operations_research::MPSolverInterface.

Definition at line 684 of file cplex_interface.cc.

◆ ExtractObjective()

void operations_research::CplexInterface::ExtractObjective ( )
virtual

Extract the objective function.

Note
The code assumes that the objective expression does not contain any non-zero duplicates.

Implements operations_research::MPSolverInterface.

Definition at line 950 of file cplex_interface.cc.

◆ IsContinuous()

virtual bool operations_research::CplexInterface::IsContinuous ( ) const
inlinevirtual

--— Misc --—

Query problem type. Remember that problem type is a static property that is set in the constructor and never changed.

Implements operations_research::MPSolverInterface.

Definition at line 114 of file cplex_interface.cc.

◆ IsLP()

virtual bool operations_research::CplexInterface::IsLP ( ) const
inlinevirtual

Returns true if the problem is continuous and linear.

Implements operations_research::MPSolverInterface.

Definition at line 115 of file cplex_interface.cc.

◆ IsMIP()

virtual bool operations_research::CplexInterface::IsMIP ( ) const
inlinevirtual

Returns true if the problem is discrete and linear.

Implements operations_research::MPSolverInterface.

Definition at line 116 of file cplex_interface.cc.

◆ iterations()

int64_t operations_research::CplexInterface::iterations ( ) const
virtual

---— Query statistics on the solution and the solve ---—

---— Query statistics on the solution and the solve ---— Number of simplex iterations

Implements operations_research::MPSolverInterface.

Definition at line 597 of file cplex_interface.cc.

◆ nodes()

int64_t operations_research::CplexInterface::nodes ( ) const
virtual

Number of branch-and-bound nodes. Only available for discrete problems.

Implements operations_research::MPSolverInterface.

Definition at line 606 of file cplex_interface.cc.

◆ ReadParameterFile()

bool operations_research::CplexInterface::ReadParameterFile ( std::string const & filename)
protectedvirtual

Return true on success and false on error.

Definition at line 1066 of file cplex_interface.cc.

◆ Reset()

void operations_research::CplexInterface::Reset ( )
virtual

---— Model modifications and extraction --—

--— Model modifications and extraction --— Resets extracted model

Instead of explicitly clearing all modeling objects we just delete the problem object and allocate a new one.

Implements operations_research::MPSolverInterface.

Definition at line 266 of file cplex_interface.cc.

◆ row_status()

MPSolver::BasisStatus operations_research::CplexInterface::row_status ( int constraint_index) const
virtual

Returns the basis status of a row.

Implements operations_research::MPSolverInterface.

Definition at line 634 of file cplex_interface.cc.

◆ SetCoefficient()

void operations_research::CplexInterface::SetCoefficient ( MPConstraint *const constraint,
MPVariable const *const variable,
double new_value,
double old_value )
virtual

Changes a coefficient in a constraint.

Changing a single coefficient in the matrix is potentially pretty slow since that coefficient has to be found in the sparse matrix representation. So by default we don't perform this update immediately but instead mark the low-level modeling object "out of sync". If we want to support incremental extraction then we MUST perform the modification immediately or we will lose it.

If row and column are both extracted then we can directly update the modeling object

If either row or column is not yet extracted then we can defer the update to ExtractModel()

Implements operations_research::MPSolverInterface.

Definition at line 466 of file cplex_interface.cc.

◆ SetConstraintBounds()

void operations_research::CplexInterface::SetConstraintBounds ( int index,
double lb,
double ub )
virtual

Modify bounds of an extracted variable.

Changing rhs, sense, or range of a constraint is not too slow. Still, doing all the updates in one large operation is faster. Note however that if we do not want to re-extract the full model for each solve (supportIncrementalExtraction is true) then we MUST update the constraint here, otherwise we lose this update information.

Constraint is already extracted, so we must update its bounds and its type.

Constraint is not yet extracted. It is sufficient to mark the modeling object as "out of sync"

Implements operations_research::MPSolverInterface.

Definition at line 415 of file cplex_interface.cc.

◆ SetDualTolerance()

void operations_research::CplexInterface::SetDualTolerance ( double value)
protectedvirtual

Implements operations_research::MPSolverInterface.

Definition at line 997 of file cplex_interface.cc.

◆ SetLpAlgorithm()

void operations_research::CplexInterface::SetLpAlgorithm ( int value)
protectedvirtual

Sets the LP algorithm : primal, dual or barrier. Note that CPLEX offers other LP algorithm (e.g. network) and automatic selection

For MIP we have to change two more parameters to specify the algorithm that is used to solve LP relaxations.

Implements operations_research::MPSolverInterface.

Definition at line 1035 of file cplex_interface.cc.

◆ SetObjectiveCoefficient()

void operations_research::CplexInterface::SetObjectiveCoefficient ( MPVariable const *const variable,
double coefficient )
virtual

Change a coefficient in the linear objective.

Nothing to do if variable was not even extracted

The objective function is stored as a dense vector, so updating a single coefficient is O(1). So by default we update the low-level modeling object here. If we support incremental extraction then we have no choice but to perform the update immediately.

Implements operations_research::MPSolverInterface.

Definition at line 537 of file cplex_interface.cc.

◆ SetObjectiveOffset()

void operations_research::CplexInterface::SetObjectiveOffset ( double value)
virtual

Change the constant term in the linear objective.

Changing the objective offset is O(1), so we always do it immediately.

Implements operations_research::MPSolverInterface.

Definition at line 559 of file cplex_interface.cc.

◆ SetOptimizationDirection()

void operations_research::CplexInterface::SetOptimizationDirection ( bool maximize)
virtual

Sets the optimization direction (min/max).

Implements operations_research::MPSolverInterface.

Definition at line 285 of file cplex_interface.cc.

◆ SetParameters()

void operations_research::CplexInterface::SetParameters ( MPSolverParameters const & param)
protectedvirtual

Set all parameters in the underlying solver.

---— Parameters --—

Implements operations_research::MPSolverInterface.

Definition at line 979 of file cplex_interface.cc.

◆ SetPresolveMode()

void operations_research::CplexInterface::SetPresolveMode ( int value)
protectedvirtual

Implements operations_research::MPSolverInterface.

Definition at line 1001 of file cplex_interface.cc.

◆ SetPrimalTolerance()

void operations_research::CplexInterface::SetPrimalTolerance ( double value)
protectedvirtual

Implements operations_research::MPSolverInterface.

Definition at line 993 of file cplex_interface.cc.

◆ SetRelativeMipGap()

void operations_research::CplexInterface::SetRelativeMipGap ( double value)
protectedvirtual

Set each parameter in the underlying solver.

Implements operations_research::MPSolverInterface.

Definition at line 984 of file cplex_interface.cc.

◆ SetScalingMode()

void operations_research::CplexInterface::SetScalingMode ( int value)
protectedvirtual

Sets the scaling mode.

Todo
: 0 is equilibrium scaling (the default), CPLEX also supports

Implements operations_research::MPSolverInterface.

Definition at line 1017 of file cplex_interface.cc.

◆ SetSolverSpecificParametersAsString()

bool operations_research::CplexInterface::SetSolverSpecificParametersAsString ( const std::string & parameters)
overridevirtual

Pass solver specific parameters in text format. The format is solver-specific and is the same as the corresponding solver configuration file format. Returns true if the operation was successful.

Default implementation returns true if the input is empty. It returns false and logs a WARNING if the input is not empty.

Reimplemented from operations_research::MPSolverInterface.

Definition at line 1290 of file cplex_interface.cc.

◆ SetVariableBounds()

void operations_research::CplexInterface::SetVariableBounds ( int index,
double lb,
double ub )
virtual

Modifies bounds of an extracted variable.

Changing the bounds of a variable is fast. However, doing this for many variables may still be slow. So we don't perform the update by default. However, if we support incremental extraction (supportIncrementalExtraction is true) then we MUST perform the update here or we will lose it.

Variable has already been extracted, so we must modify the modeling object.

Variable is not yet extracted. It is sufficient to just mark the modeling object "out of sync"

Implements operations_research::MPSolverInterface.

Definition at line 290 of file cplex_interface.cc.

◆ SetVariableInteger()

void operations_research::CplexInterface::SetVariableInteger ( int var_index,
bool integer )
virtual

Modifies integrality of an extracted variable.

Note
The type of the model (continuous or mixed integer) is defined once and for all in the constructor. There are no dynamic changes to the model type.

Changing the type of a variable should be fast. Still, doing all updates in one big chunk right before solve() is usually faster. However, if we support incremental extraction (supportIncrementalExtraction is true) then we MUST change the type of extracted variables here.

Variable is extracted. Change the type immediately.

Todo
: Should we check the current type and don't do anything in case the type does not change?

Implements operations_research::MPSolverInterface.

Definition at line 319 of file cplex_interface.cc.

◆ Solve()

MPSolver::ResultStatus operations_research::CplexInterface::Solve ( MPSolverParameters const & param)
virtual

--— Solve --— Solve the problem using the parameter values specified.

Delete chached information

Set incrementality

Extract the model to be solved. If we don't support incremental extraction and the low-level modeling is out of sync then we have to re-extract everything. Note that this will lose MIP starts or advanced basis information from a previous solve.

Set log level.

Set parameters.

Note
We must invoke SetSolverSpecificParametersAsString() first. Its current implementation invokes ReadParameterFile() which in turn invokes CPXXreadcopyparam(). The latter will overwrite all current parameter settings in the environment.

Solve. Do not CHECK_STATUS here since some errors (for example CPXERR_NO_MEMORY) still allow us to query useful information.

Disable screen output right after solve

Note
We do not return immediately since there may be information to grab (for example an incumbent)

Figure out what solution we have.

Get problem dimensions for solution queries below.

Capture objective function value.

Capture primal and dual solutions

If there is a primal feasible solution then capture it.

MIP does not have duals

Continuous problem.

Map CPLEX status to more generic solution status in MPSolver

To be consistent with the other solvers.

Implements operations_research::MPSolverInterface.

Definition at line 1075 of file cplex_interface.cc.

◆ SolverVersion()

std::string operations_research::CplexInterface::SolverVersion ( ) const
virtual

Returns a string describing the underlying solver and its version.

We prefer CPXXversionnumber() over CPXXversion() since the former will never pose any encoding issues.

Implements operations_research::MPSolverInterface.

Definition at line 246 of file cplex_interface.cc.

◆ underlying_solver()

virtual void * operations_research::CplexInterface::underlying_solver ( )
inlinevirtual

Returns the underlying solver.

Implements operations_research::MPSolverInterface.

Definition at line 126 of file cplex_interface.cc.

◆ ValidFileExtensionForParameterFile()

std::string operations_research::CplexInterface::ValidFileExtensionForParameterFile ( ) const
protectedvirtual

Definition at line 1071 of file cplex_interface.cc.


The documentation for this class was generated from the following file: