Referencing constraints and retrieving their dual (Pi) values with C++
AnsweredHello,
I am using Gurobi with C++.
Once I introduced the constraints, I would like to retrieve their dual (Pi) values.
For instance,
//Adding x variables
x = new GRBVar*[n];
for (k = 0; k < n; k++) {
x[k] = new GRBVar*[n];
for (j = 0; j < n; j++)
x[k][j]= model.addVar(0.0, 1.0, c[j][k], GRB_CONTINUOUS);
}
//Adding the constraints
for (k = 1; k < n; k++) {
GRBLinExpr u=0;
for (j = 1; j < n; j++)
u +=x[k][j];
model.addConstr(u == 1);
}
I am wondering how to reference this constraint and retrieve its dual values after optimizing.
-
Official comment
This post is more than three 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 why not try our AI Gurobot?. -
Hi Ali,
In order to retrieve the dual values of your constraints in the code above, you could first store these constraints in an array and use this array later to get the dual values. I am sharing a code snippet below printing the retrieved dual variables after optimization.
GRBConstr* constrs = new GRBConstr[n];
for (k = 1; k < n; k++) {
GRBLinExpr u=0;
for (j = 1; j < n; j++)
u +=x[k][j];
constrs[k] = model.addConstr(u == 1);
}
model.optimize();
for (k = 1; k < n; k++) {
cout << "Pi of constraint " << k << " is " << constrs[k].get(GRB_DoubleAttr_Pi) << endl;
}Best regards,Elisabeth-1 -
It works!
Thanks a lot Elisabeth
Best regards
Ali
0 -
Hello
I am trying to extend the methodology presented here to python, but have not been succesfull.
Here is a section of my code:
I have also tried the following without success:
fixed = model.fixed()
fixed.Params.QCPDual = 1
fixed.optimize()
constrs = fixed.getConstrs()
shadow_price = fixed.getAttr(GRB.Attr.QCPi) #this works but there is no information about associated constraints to QCPi values.
sh_pr = np.zeros((len(shadow_price),2))
sh_p_i = 0
for ci in range(0,len(constrs)+1):
try:
sh_pr[sh_p_i,0] = constrs[ci].getAttr(GRB.Attr.QCPi) #this does not work
sh_pr[sh_p_i,1] = constrs[ci].index
sh_p_i = sh_p_i + 1
except Exception:
passI appreciate any comments.
0 -
The discussion about applying this methodology in Python is continued in the post Dual value Pi and QCPi for specified constraint - python.
0
Post is closed for comments.
Comments
5 comments