How to multiply two binary gurobi variables using Java?
AnsweredHello,
I am wondering how I can multiply two gurobi variables in Java! For example, in the following code, I am going to multiply m1, as gurobi binary variable to each gurobi continuous variable in expr10. I would appreciate your guidance!
Best regards,
Hadi
GRBLinExpr expr10 = new GRBLinExpr();
GRBLinExpr expr11 = new GRBLinExpr();
((Process) next).setStart_time(this.model.addVar(0.0, 1000, 0, GRB.CONTINUOUS, "StartingTime"+ ((Process) next).getName()));
GRBVar m1 = model.addVar( 0.0, 1.0, 0.0, GRB.BINARY, "M");
expr10.addTerm(1, listofPairedProcesses.get(0).getStart_time() );
expr10.addTerm(1, listofPairedProcesses.get(1).getStart_time());

Hi Hadi,You can define a Gurobi quadratic expression object (GRBQuadExpr) and iterate through the terms in the GRBLinExpr object already defined and multiply each term by the binary variable \(\texttt{m1}\). Please see the snippet below as an example:
GRBQuadExpr quad_expr = new GRBQuadExpr();
for (int i=0; i < expr10.size(); ++i) {
double coeff = expr10.getCoeff(i);
GRBVar var_1 = expr10.getVar(i);
quad_expr.addTerm(coeff, var_1, m1);
}Best regards,Maliheh1 
Dear Maliheh,
Thanks for your reply! If I want to multiply two gurobi binary variables e.g. k = m1*m2 and then multiply k to the expr10, how can I proceed? I've tried the same method as you explained but it didn't work!
I would appreciate your help!
0 
Hi Hadi,
Sorry for the delay in getting back to you.
It should work. I tested the snippet below and it works. Could you please try modifying your code based on the example below and rerun it again?
GRBVar m1 = model.addVar(0.0, 1.0, 0.0, GRB.BINARY, "m1");
GRBVar m2 = model.addVar(0.0, 1.0, 0.0, GRB.BINARY, "m2");
GRBVar k = model.addVar(0.0, 1.0, 0.0, GRB.BINARY, "k");
// Model k = m1 * m2
GRBQuadExpr quad_expr_k = new GRBQuadExpr();
quad_expr_k.addTerm(1, m1, m2);
model.addQConstr(quad_expr_k, GRB.EQUAL, k, "c1");
// Multiply k by the linear expression
GRBQuadExpr quad_expr = new GRBQuadExpr();
for (int i=0; i < expr10.size(); ++i) {
double coeff = expr10.getCoeff(i);
GRBVar var_1 = expr10.getVar(i);
quad_expr.addTerm(coeff, var_1, k);
}Best regards,
Maliheh
0 
Dear Maliheh,
It worked, I would really appreciate your help!
Best regards,
Hadi
0
Please sign in to leave a comment.
Comments
4 comments