#!/usr/bin/env python3# Copyright 2025, Gurobi Optimization, LLC# Want to cover four different sets but subject to a common budget of# elements allowed to be used. However, the sets have different priorities to# be covered; and we tackle this by using multi-objective optimization.importgurobipyasgpfromgurobipyimportGRBimportsystry:# Sample dataGroundset=range(20)Subsets=range(4)Budget=12Set=[[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,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,1,1,0,1,1,0,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]# Create initial modelmodel=gp.Model("multiobj")# Initialize decision variables for ground set:# x[e] == 1 if element e is chosen for the covering.Elem=model.addVars(Groundset,vtype=GRB.BINARY,name="El")# Constraint: limit total number of elements to be picked to be at most# Budgetmodel.addConstr(Elem.sum()<=Budget,name="Budget")# Set global sense for ALL objectivesmodel.ModelSense=GRB.MAXIMIZE# Limit how many solutions to collectmodel.setParam(GRB.Param.PoolSolutions,100)# Set and configure i-th objectiveforiinSubsets:objn=sum(Elem[k]*Set[i][k]forkinrange(len(Elem)))model.setObjectiveN(objn,i,SetObjPriority[i],SetObjWeight[i],1.0+i,0.01,"Set"+str(i))# Save problemmodel.write("multiobj.lp")# Optimizemodel.optimize()model.setParam(GRB.Param.OutputFlag,0)# Status checkingstatus=model.Statusifstatusin(GRB.INF_OR_UNBD,GRB.INFEASIBLE,GRB.UNBOUNDED):print("The model cannot be solved because it is infeasible or unbounded")sys.exit(1)ifstatus!=GRB.OPTIMAL:print(f"Optimization was stopped with status{status}")sys.exit(1)# Print best selected setprint("Selected elements in best solution:")selected=[eforeinGroundsetifElem[e].X>0.9]print(" ".join(f"El{e}"foreinselected))# Print number of solutions storednSolutions=model.SolCountprint(f"Number of solutions found:{nSolutions}")# Print objective values of solutionsifnSolutions>10:nSolutions=10print(f"Objective values for first{nSolutions} solutions:")foriinSubsets:model.setParam(GRB.Param.ObjNumber,i)objvals=[]foreinrange(nSolutions):model.setParam(GRB.Param.SolutionNumber,e)objvals.append(model.ObjNVal)print(f"\tSet{i}"+"".join(f"{objval:6g}"forobjvalinobjvals[:3]))exceptgp.GurobiErrorase:print(f"Error code{e.errno}:{e}")exceptAttributeErrorase:print(f"Encountered an attribute error:{e}")
Help and Feedback