简体   繁体   中英

Gurobi Python Programming_ solve an optimization problem n times with a contraint that varies for a constant (eps)

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

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

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