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
-
Official comment
This post is more than two years old. Some information may not be up to date. For current information, please check the Gurobi Documentation or Knowledge Base. If you need more help, please create a new post in the community forum, or try Gurobot, our chatbot interface offering instant, expert-level support. -
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
Post is closed for comments.
Comments
2 comments