Cannot set objective function in Gurobi model C++
AnsweredHello,
I have tried to set the objective function in my model based on a quadatric expression GRBQuadExpr that i return from a function in different file other than Main.cpp. But when i run the program it terminates with error 20001 "Variable not in model".
//test.cpp
typedef std::vector<std::pair<float, float>> vec_pair;
namespace PDPTW_Init
{
int vehicles,customers;
vehicles = 10;
customers = 101;
// This is the initialization of d_matrix
GRB_vec2d init_d_matrix(GRBModel& model,vec_pair coords)
{
GRB_vec2d c_matrix(customers, std::vector<GRBVar>(customers));
for (int i = 0; i < customers; i++)
{
c_matrix[i][i] = model.addVar(0, GRB_INFINITY, 0, GRB_CONTINUOUS, "dist from x " + std::to_string(i) + " to " + std::to_string(i)); // Distance from self is zero
for (int j = 0; j < customers && j!=i; j++)
{
double dist_i_j = sqrt(pow((coords[i].first - coords[j].first), 2) + pow((coords[i].second - coords[j].second), 2));
c_matrix[i][j] = model.addVar(0, GRB_INFINITY,
dist_i_j, GRB_CONTINUOUS,
"dist from x " + std::to_string(i) + " to " + std::to_string(j));
}
}
return c_matrix;
}
GRBQuadExpr get_objective(std::vector<std::vector<GRBVar>> c_matrix, GRBVar*** x)
{
GRBQuadExpr obj = 0.0;
for (int k = 0; k < vehicles; k++)
{
for (int i = 0; i < customers; i++)
{
for (int j = 0; j < customers; j++)
{
obj += c_matrix[i][j] * x[i][j][k];
}
}
}
return obj;
}
}
// main.cpp
int main(int argc, char* argv[])
{
GRBEnv env = GRBEnv();
GRBModel model = GRBModel(env);
obj = PDPTW_Init::get_objective(d_matrix, x);
model.setObjective(obj,GRB_MINIMIZE); // Here is the error
}
Thanks in advance.
0
-
Hi Giorgos,
In your code snippet, I cannot find a call to \(\texttt{init_d_matrix}\), which would initialize the matrix entries and create the \(\texttt{x}\) variables.
Best regards,
Jaromił0
Please sign in to leave a comment.
Comments
1 comment