简体   繁体   中英

Gurobi: how to add a constraint x1*x2*x3

I wish to add a constraint n1 = x1 * x2 *x3 in Gurobi, where x1 , x2 and x3 are variables with 0 or 1. Unfortunately, can not find the solution.

Can someone help me?

You are trying to create a seemingly non-linear constraint on binary variables. You can model this as a series of linear constraints by noting the n will have the value 1 if and only if x1, x2, and x3 are all 1.

// only if part
model.addConstr(n, GRB.LESS_EQUAL, x1);
model.addConstr(n, GRB.LESS_EQUAL, x2);
model.addConstr(n, GRB.LESS_EQUAL, x3);

// if part
GRBLinExpr all_three;
all_three.addTerm(1.0, x1);
all_three.addTerm(1.0, x2);
all_three.addTerm(1.0, x3);
all_three.addConstrant(-2);
model.addConstr(n, GRB.GREATER_EQUAL, all_three);

This adds the constraints n >= x1 + x2 + x3 - 2 and n <= min(x1, x2, x3) .

n1<=x1
n1<=x2
n1<=x3
2+n1>=x1+x2+x3

If any of the of the x are 0, then n will be force to zero. If all are 1, n is forced to 1.

Edit Since Gurobi recognizes binary variables, you could just use

3*n1<=x1+x2+x3
2+n1>=x1+x2+x3

The first only allow 0 and 1 while this would allow fractional values if not for the binary requirement.

EDIT The constraint

n3 = x2 * (n1 + n2 - n1 * n2) + x1 * (n1 - n2) *(n1 - n2)

appears to be trying to enforce the logic

IF n1 AND n2: 
    n3 = x2

IF n1 XOR n2:
    n3 = x1

IF (NOT n1) AND (NOT n2):
    n3 = 0

Since it the standard rule for expressing boolean logic operations in zero-one integer linear programming (ILP) take the form of x1 AND x2 IMPLIES y1 , I reconstructed the above to read

n1 AND n2 IMPLIES i1
n1 XOR n2 IMPLIES i2
(NOT n1) AND (NOT n2) IMPLIES i3   

Constructing the constraints for i1, i2, i3 is given below

IF n1 AND n2, THEN i1 
    i1 ≥ n1 + n2 − 1
    i1 ≤ n1
    i1 ≤ n2
    0 ≤ i1 ≤ 1

IF n1 XOR n2, THEN i2
    i2 ≤ n1 + n2
    i2 ≥ n1 − n2
    i2 ≥ n2 − n1
    i2 ≤ 2 − n1 − n2
    0 ≤ i2 ≤ 1

IF NOT n1 AND NOT n2, THEN i3
    i3 ≥ 1 - n1 - n2
    i3 ≤ (1 - n1)
    i3 ≤ (1 - n2)
    0 ≤ i3 ≤ 1

This gives use three mutually exclusive indicators and the original problem can be rewritten as

-(1 - i1) ≤ n3 - x2 ≤ (1 - i1)
-(1 - i2) ≤ n3 - x1 ≤ (1 - i2)
-(1 - i3) ≤ n3 ≤ (1 - i3)

Simplify way to convert binary string to integer. And, multiply it. Is it not OK?

int x1 = Integer.parseInt("101011", 2);
int x2 = Integer.parseInt("00010", 2);
int x3 = Integer.parseInt("000101", 2);
int n1 = x1 * x2 * x3;
System.out.println(n1);

Update

I don't know Gurobi , but

  GRBVar x1 = model.AddVar(0.0, 1.0, 0.0, GRB.BINARY, "x1");
  GRBVar x2 = model.AddVar(0.0, 1.0, 0.0, GRB.BINARY, "x2");
  GRBVar x3 = model.AddVar(0.0, 1.0, 0.0, GRB.BINARY, "x3");

Example

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM