0

I am trying to add a piecewise function to my objective function in Gurobi and am not sure if I need to manually assign it or if Gurobi will figure it out.

I have added this piecewise function in Gurobi uusing this code that I got from this source https://support.gurobi.com/hc/en-us/community/posts/4408013572497-Piecewise-Objective-function-and-Piecewise-constraints-:

m = gp.Model("test")
quantity = m.addVar(lb=5, ub=100, vtype=GRB.INTEGER, name="quantity")
cost = m.addVar(lb=0.5, ub=2, vtype=GRB.CONTINUOUS, name="cost")
m.addGenConstrPWL(quantity, cost, [1000, 4800, 4800.01, 15000, 1500.01, 30000], [5.2, 5.2, 5, 5, 4.6, 4.6])

I am wondering how I fit this into the objective function, can I store it as a variable and add it? Will it automatically be added when I add the objective function after? This is my first time using Gurobi.

enter image description here

Reinderien
  • 11,755
  • 5
  • 49
  • 77
Zhi Z
  • 1
  • 1
    Does it work? That line of code should have added a piecewise constraint. – Tim Roberts Aug 01 '23 at 03:30
  • 1
    I have the same question as @TimRoberts: do you need a piecewise objective or a piecewise constraint? – Greg Glockner Aug 01 '23 at 15:57
  • @GregGlockner I think it would be a piecewise objective. Looking at the objective function I provided I need the piecewise value as a part of my objective function as the variable W(xij) – Zhi Z Aug 02 '23 at 16:18

1 Answers1

0

Use gurobipy.Model.setPWLObj() to set a piecewise linear objective function. Here is one way to code your example:

x = [1000, 4800, 15000, 30000]
c = [5.2, 5.2, 5.0, 4.6]
y = [0]*len(x)

y[0] = c[0]*x[0]
for i in range(1,4):
  y[i] = c[i]*(x[i]-x[i-1]) + y[i-1]

m.setPWLObj(quantity, x, y)
Greg Glockner
  • 5,433
  • 2
  • 20
  • 23