samie
samie

Reputation: 191

how to define the numerical value for objective in gurobi

I am using gurobi and in my object I want to maximize difference between two variables

X1 - X2

But it is not important which variable is bigger so I want to use numerical value of this difference:

|X1 - X2|

How can I define this type of objective in gurobi.

Blow is a semi code of an implementation that I want to do:

m = Model("mip1")
Edges = tuplelist([(1,2),(1,3),(3,4),(3,5),(3,6),(5,6),(6,7),
               (8,9),(9,10),(11,12),(12,10),(12,13),(14,10),
               ])

x = m.addVars(Edges, lb=0.0, ub=1.0, name = "x")
m.setObjectiveN(quicksum(x[w,s] for w,s in Edges),0)


-------my second variables and objective----

y = m.addVars(2, vtype=GRB.BINARY, name="y")
y[0] = quicksum(x.select(1,'*'))
y[1] = quicksum(x.select(8,'*'))

m.setObjectiveN(|y[0]-y[1]|,1)

m.optimize()   

Upvotes: 1

Views: 365

Answers (1)

joni
joni

Reputation: 7157

Gurobi only accepts absolute values in the constraints, so you could do it like this:

# Define two helper variables
z = m.addVar(name="z")
h = m.addVar(name="h")

m.addConstr(h == y[0]-y[1])  # h = y[0]-y[1]
m.addConstr(z == abs_(h))    # z == |h| == | y[0] - y[1] |
m.setObjectiveN(z, 1)        # Maximize z = |h| = |y[0]-y[1]|

where _abs() is a general constraint.

Upvotes: 1

Related Questions