Home > Blockchain >  Gurobi Python Programming_ solve an optimization problem n times with a contraint that varies for a
Gurobi Python Programming_ solve an optimization problem n times with a contraint that varies for a

Time:08-04

Can you help me understand why if I compute this code, I always get the same solution (n times) instead of having different solution for each value of eps?

from gurobipy import GRB
from gurobipy import Model
import math 

m = Model('pyOA_e2')
UB = 2
LB = -3

x = m.addVar(name = 'x', lb = -2, ub= 2)
y = m.addVar(name = 'y', lb=-2, ub = 2)
u = m.addVar(name = 'u', lb = -2, ub = 2)
z = m.addVar(name = 'z')
m.update()

n=11
eps_min = -math.sqrt(3)   math.exp(-2)
eps_max =  math.exp(2)
eps =[eps_min]
for i in range(n-1):
    eps = [eps[i]   (eps_max-eps_min)/(n-1)]
i= 1  i
print(eps)


e=0
while e <= len(eps)-1:     
    m.addGenConstrExp(u, z)
    m.addConstr(y   z - eps[e]<=0)
    m.addConstr(x**2   (1/3)*(y**2) - 1 <=0)
    m.setObjective(x-u)
    m.optimize()
    if m.Status == GRB.OPTIMAL:
        LB = m.ObjVal
        m.printAttr('x')
        print(m.ObjVal)
        print(eps[e])   
    e=e 1
    print(e)

The code inside the while loop works: if I change manually the eps value and compute the code for each value I obtain what I want. But I have trouble in automatising it in a while or for loop.

Thank you. Best, Paola

CodePudding user response:

I hope you realize you are just adding (not replacing) new constraints in each iteration. Print the LP file for the last iteration to see what you generated.

The solution does not change because the first eps[0] is the tightest. See the LP file for that.

Note that there is a Gurobi manual with lots of information.

  1. To write an LP file see: https://www.gurobi.com/documentation/9.5/refman/py_model_write.html
  2. To change an RHS see: https://www.gurobi.com/documentation/9.5/refman/rhs.html
  • Related