Solving an optimization problem
The basic search strategy in CP Optimizer can be used to solve optimization problems.
The basic algorithm for solving a model is invoked by
calling the method solve, a member function
of the optimizer object. (For example, in the C++ API,
this is IloCP::solve. In the Java™ API, this method is IloCP.solve. In the C# API, this
method is CP.Solve.) This function returns
true (IloTrue in the C++ API) when the engine
has found an optimal solution. If the model has no objective function,
then this call returns true when a solution is found. The function
returns false (IloFalse in the C++ API)
when the problem has no solution.
Consider the following model with 3 integer variables, written in the C++ API:
IloIntVar x(env, 0, 7, "x");
IloIntVar y(env, 0, 7, "y");
IloIntVar z(env, 0, 7, "z");
IloIntVarArray all(env, 3, x, y, z);
model.add(IloMinimize(env, IloSum(all)));
model.add(IloAllDiff(env, all));
model.add(y == IloElement(IloIntArray(env, 7, 3, 7, 8, 8, 0, 1, 4), x));
To solve the problem represented by this model, you can
call the method IloCP::solve, like this:
IloCP cp(model);
cp.setParameter(IloCP::LogVerbosity, IloCP::Quiet);
if (cp.solve()){
cp.out() << " An optimal solution has been found"
<< ", objective value = " << cp.getObjValue()
<< ", x = " << cp.getValue(x)
<< ", y = " << cp.getValue(y)
<< ", z = " << cp.getValue(z) << std::endl;
} else {
cp.out() << " The problem has no solution " << std::endl;
}
In this example, the search log output is deactivated
for the sake of brevity. Information regarding the search log is presented
in the section The search log. The method getValue, a member function of the optimizer object,
takes a decision variable as an argument and returns the value of
that variable in the solution that was found. The method getObjValue, a member function of the optimizer
object, returns the value of the objective for this solution.
Running this code produces the output:
An optimal solution has been found, objective value = 4, x = 0, y = 3, z = 1
In the C++ API of CP Optimizer, you use
the class IloCP and the methods IloCP::solve, IloCP::getValue and IloCP::getObjValue.
In the Java API of
CP Optimizer, you use the class IloCP and
the methods IloCP.solve, IloCP.getValue and IloCP.getObjValue.
In the C# API of CP Optimizer, you use
the class CP and the methods CP.Solve and CP.GetValue and the member CP.ObjValue.