0

I am trying to solve an optimization problem in python using the gurobi solver.

Problem background: I can buy and sell goods on a market with given Prices P for a series of time steps. For a start, I can only buy/sell one good and my warehouse has storage capacity for up to 2 goods at a time. I decided to add a Variables x for each time step that can either be -1 (buy), 0 (do nothing) or 1 (sell). The restriction thus is that the sum over all x[i] in each time step has to be >=-2 and <=0 (“never sell more than you have bougth before)

I manged to run the following code:

P =[1,3,5,4,5,2,2,4,6]
x = m.addVars(6,lb=-1, ub=1, vtype=GRB.INTEGER, name="x")
m.addConstr((quicksum(x[i] for i in range(len(P))) <=0), name=("con.format(i)"))
m.addConstr((quicksum(x[i] for i in range(len(P))) >=-2), name=("Const1"))
m.setObjective(quicksum(x[i]*P[i] for i in range(len(P))) , GRB.MAXIMIZE)

However, the result of the optimization {0: -1.0, 1: -1.0, 2: 1.0, 3: 1.0, 4: 1.0, 5: -1.0, 6: -1.0, 7: 0.0, 8: 1.0} shows that the only the overall solution meets the requirements, but in between, the algorithm sells more good than it had purchased before (e.g. periode 5). So, I need to adapt my code in a way that it introduces a contraint for each time step [i], which ensures that the sum of all privious steps [1 to i] also meet the constrains. I found some similar problem (e.g. here: Gurobi Python: how to write nested sum in a constraint) but none could help me with my specific problem of how to calculate the interim sums in each step. However, I hope you can!  Thanks in advance and best regards!

James
  • 23
  • 5

1 Answers1

1

According to your list P it should be:

x = m.addVars(9, lb=-1, ub=1, vtype=GRB.INTEGER, name="x")

To answer your question: if I understood your needs correctly, you could use the m.addConstrs method like this:

m.addConstrs(quicksum(x[i] for i in range(k)) <= 0 for k in range(1, len(P)))
m.addConstrs(quicksum(x[i] for i in range(k)) >= -2 for k in range(1, len(P)))

Solution:

x[0] -1.0
x[1] -1.0
x[2] 1.0
x[3] 0.0
x[4] 1.0
x[5] -1.0
x[6] -1.0
x[7] 1.0
x[8] 1.0
joni
  • 6,840
  • 2
  • 13
  • 20
  • Thank you! That actually works as intended. Sic, I thought I tried every combination of for-loops within the addContrs-Method but did not consider your way of providing k at the very end of the statement. Thank you again, it was rather desperate after 2 days of trying out all sorts of things. – James Aug 14 '18 at 07:51