Slow constraints addition in Python vs. C++
回答済みHello,
I'm getting troubles with my model. Here is my code :
T = model.addMVar((numnonzero,), vtype=GRB.BINARY)
for s1 in range(numnonzero):
for s2 in range(s1+1,numnonzero):
row1 = nonzero[s1][0]
col1 = nonzero[s1][1]
row2 = nonzero[s2][0]
col2 = nonzero[s2][1]
if (row1 == row2 or col1 == col2 or (X[row1][col2] > 0.001 and X[row2][col1] > 0.001)):
model.addConstr(T[s1]+T[s2]<=1)
where nonzero is the indice set of the non-zero values of X and numnonzero is the length of this set. For some 20-by-20 matrices, it takes more than 20 seconds only to build this model (even if the optimization itself is quite faster). For example, I have the same model in C++ and the time to construct the model is almost 0, here is the code :
int indices[2]
double coefficients[2] = {1.0,1.0};
for (std::size_t s1 = 0; s1 < numnonzero; ++s1):
{
for (std::size_t s2 = s1 + 1; s2 < numnonzero; ++s2)
{
std::size_t row1 = nonzeros[s1].row;
std::size_t col1 = nonzeros[s1].col;
std::size_t row2 = nonzeros[s2].row;
std::size_t col2 = nonzeros[s2].col;
if (row1 == row2 || col1 == col2 || (isNonzero(row1,col2) && isNonzero(row2,col1)))
{
indices[0]=s1;
indices[1]=s2;
GRBaddconstr(model,2,&indices[0],&coefficients[0], '<', 1.0, nullptr);
}
}
}
So my question is: why does it take so long in Python while I almost can get it instantly in my C++ model, and how to manage this ?
Have a good day,
Timothy
-
正式なコメント
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 Timothy,
It looks like you are mixing matrix-friendly and term-based modeling in Python.
Did you try to use Model.addVars() instead of Model.addMVar() ?Best regards,
Marika0 -
Hello Marika, thanks for this answer!
I first wrote a "matrix-based modeling" but the time to build the model was even worse, so I tried like this. However, just using Model.addVars() makes the generation 50 times faster, thank you!
0
投稿コメントは受け付けていません。
コメント
3件のコメント