How to assign numeric multiplier to a variable in or-tools (C++)

Viewed 93
std::vector<const MPVariable *> P(mP);
for (int a = 1; a <= mP; a++)
    P[a - 1] = solver->MakeBoolVar("P"+std::to_string(a));

for (int a = 1; a <= mP; a++)
{
    LinearExpr eq;
    for (int b = 1; b <= T; b++)
    {
      ; //eq += ... ;
    }
    eq -=  T * P[a - 1]; // error; however, eq -=  P[a - 1] is okay.
    solver->MakeRowConstraint(eq <= 0.0);
}

eq -= T * P[a - 1] gives error. However, eq -= P[a - 1] is okay. T is an int.

Error msg:

 invalid operands of types ‘int’ and ‘__gnu_cxx::__alloc_traits<std::allocator<const operations_research::MPVariable*>, const operations_research::MPVariable*>::value_type’ {aka ‘const operations_research::MPVariable*’} to binary ‘operator*’

How to assign a numeric multiplier (T) to the variable (P[a - 1])?

Additionally, how to print the LP model that was generated, so that I can debug it?

1 Answers

Edit: I had originally erroneously showed the code for the CP-SAT Solver, not the MIP solver, corrected here.

In the documentation at https://github.com/google/or-tools/blob/stable/ortools/linear_solver/linear_expr.h#L174 I can see an overloading of the simple arithmetic operators for LinearExpr as follows:

LinearExpr operator+(LinearExpr lhs, const LinearExpr& rhs);
LinearExpr operator-(LinearExpr lhs, const LinearExpr& rhs);
LinearExpr operator*(LinearExpr lhs, double rhs);
LinearExpr operator/(LinearExpr lhs, double rhs);
LinearExpr operator*(double lhs, LinearExpr rhs);

There is no overloading for multiplication with int, you'll need to use a double for the factor instead of an int like this:

double doubleT = double(T);
eq -= doubleT * P[a - 1];
Related