manbet体育手机客户端


gc_pwl_func.py


#!# #最大化2 x + y #受exp(x) + 4 sqrt(y) <= 9 #狗万app足彩 x, y >= 0 # #我们展示两种方法来解决这个问题:1)使用分段线性方法处理一般的函数#约束(如exp和sqrt)。# a)添加两个变量# u = exp(x) # v = sqrt(y) # b)计算点(x, u)的u = exp(x)为某步长(例如,x # = 0,1e - 3,2e -3,…在某步长(例如,y = 0,1e - 3,2e -3,…ymax)。我们需要# compute xmax和ymax(这个例子很简单,但是这个#并不适用于一般情况)。# c)使用这些点添加两个类型#分段线性的一般约束。# # 2)直接使用Gurobis内置的通用函数约束(EXP #和POW)。在这里,我们不需要计算点和最大可能值,这将由Gurobi内部完成。在这个#方法中,我们展示了如何“放大”最优的解决方案并#收紧公差以提高解决方案的质量。#从gurobipy进口进口数学进口gurobipy gp伽马线暴def printsol (m, x, y, u, v):打印(x =”+ str (x.x) +, u = + str (u.x))打印(y = ' + str (y.x) +, v = + str (v.x))打印(' Obj = ' + str (m.objVal)) #计算违反exp (x) + 4倍根号(y) < = 9 vio = math.exp (x.x) + 4 * math.sqrt (y.x) - 9如果vio < 0: vio = 0 print('Vio = ' + str(vio)) try: # Create a new model m = gp.Model() # Create variables x = m.addVar(name='x') y = m.addVar(name='y') u = m.addVar(name='u') v = m.addVar(name='v') # Set objective m.setObjective(2*x + y, GRB.MAXIMIZE) # Add constraints lc = m.addConstr(u + 4*v <= 9) # Approach 1) PWL constraint approach xpts = [] ypts = [] upts = [] vpts = [] intv = 1e-3 xmax = math.log(9) t = 0.0 while t < xmax + intv: xpts.append(t) upts.append(math.exp(t)) t += intv ymax = (9.0/4)*(9.0/4) t = 0.0 while t < ymax + intv: ypts.append(t) vpts.append(math.sqrt(t)) t += intv gc1 = m.addGenConstrPWL(x, u, xpts, upts, "gc1") gc2 = m.addGenConstrPWL(y, v, ypts, vpts, "gc2") # Optimize the model m.optimize() printsol(m, x, y, u, v) # Approach 2) General function constraint approach with auto PWL # translation by Gurobi # restore unsolved state and get rid of PWL constraints m.reset() m.remove(gc1) m.remove(gc2) m.update() # u = exp(x) gcf1 = m.addGenConstrExp(x, u, name="gcf1") # v = x^(0.5) gcf2 = m.addGenConstrPow(y, v, 0.5, name="gcf2") # Use the equal piece length approach with the length = 1e-3 m.params.FuncPieces = 1 m.params.FuncPieceLength = 1e-3 # Optimize the model m.optimize() printsol(m, x, y, u, v) # Zoom in, use optimal solution to reduce the ranges and use a smaller # pclen=1-5 to solve it x.lb = max(x.lb, x.x-0.01) x.ub = min(x.ub, x.x+0.01) y.lb = max(y.lb, y.x-0.01) y.ub = min(y.ub, y.x+0.01) m.update() m.reset() m.params.FuncPieceLength = 1e-5 # Optimize the model m.optimize() printsol(m, x, y, u, v) except gp.GurobiError as e: print('Error code ' + str(e.errno) + ": " + str(e)) except AttributeError: print('Encountered an attribute error')