multibj.py.
#!/ usr / bin / env python3.7#版权所有2021,guro狗万app足彩bi优化,llc#想要覆盖三个不同的集,但受允许使用的#元素的共同预算。但是,该集合对#有不同的优先级;我们通过使用多目标优化来解决这个问题。从Gurobipy导入Grb导入Sys导入Gurobipy作为GP导入SYS尝试:#示例数据磨设=范围(20)子集=范围(4)预算= 12 SET = [[1,1,1,1,1,1,1,1,1,1,1,0,0,0,0,0,0,0,0,0,0,0,0],[0,0,0,0,0,1,1,1,1,1,1,0,0,0,0,0,1,1,1,1,1],[0,0,0,1,1,0,1,1,0,0,0,0,0,0,1,1,0,1,1,0,0,0,0,1,1,1,0,0,0,1,1,1,0,0,0,1,1,1,0,0]] setobjpriority = [3,2,2,1] setobjweight = [1.0,0.25,1.25,1.0]#创建初始模型模型= gp.model('multiob')#初始化地面集的决策变量:#x [e]== 1如果为覆盖选择元素E.elem = model.advars(proundset,vtype = grb.binary,name ='el')#约束:限制要选择的元素总数为大多数#pupget model.addconstr(elem.sum()<=预算, name='Budget') # Set global sense for ALL objectives model.ModelSense = GRB.MAXIMIZE # Limit how many solutions to collect model.setParam(GRB.Param.PoolSolutions, 100) # Set and configure i-th objective for i in Subsets: objn = sum(Elem[k]*Set[i][k] for k in range(len(Elem))) model.setObjectiveN(objn, i, SetObjPriority[i], SetObjWeight[i], 1.0 + i, 0.01, 'Set' + str(i)) # Save problem model.write('multiobj.lp') # Optimize model.optimize() model.setParam(GRB.Param.OutputFlag, 0) # Status checking status = model.Status if status in (GRB.INF_OR_UNBD, GRB.INFEASIBLE, GRB.UNBOUNDED): print("The model cannot be solved because it is infeasible or " "unbounded") sys.exit(1) if status != GRB.OPTIMAL: print('Optimization was stopped with status ' + str(status)) sys.exit(1) # Print best selected set print('Selected elements in best solution:') selected = [e for e in Groundset if Elem[e].X > 0.9] print(" ".join("El{}".format(e) for e in selected)) # Print number of solutions stored nSolutions = model.SolCount print('Number of solutions found: ' + str(nSolutions)) # Print objective values of solutions if nSolutions > 10: nSolutions = 10 print('Objective values for first ' + str(nSolutions) + ' solutions:') for i in Subsets: model.setParam(GRB.Param.ObjNumber, i) objvals = [] for e in range(nSolutions): model.setParam(GRB.Param.SolutionNumber, e) objvals.append(model.ObjNVal) print('\tSet{} {:6g} {:6g} {:6g}'.format(i, *objvals)) except gp.GurobiError as e: print('Error code ' + str(e.errno) + ": " + str(e)) except AttributeError as e: print('Encountered an attribute error: ' + str(e))