# 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.library(Matrix)library(gurobi)# define primitive datagroundSetSize<-20nSubSets<-4Budget<-12Set<-list(c(1,1,1,1,1,1,1,1,1,1,0,0,0,0,0,0,0,0,0,0),c(0,0,0,0,0,1,1,1,1,1,0,0,0,0,0,1,1,1,1,1),c(0,0,0,1,1,0,1,1,0,0,0,0,0,1,1,0,1,1,0,0),c(0,0,0,1,1,1,0,0,0,1,1,1,0,0,0,1,1,1,0,0))SetObjPriority<-c(3,2,2,1)SetObjWeight<-c(1.0,0.25,1.25,1.0)# Initialize modelmodel<-list()model$modelsense<-'max'model$modelname<-'multiobj'# Set variables, all of them are binary, with 0,1 bounds.model$vtype<-'B'model$lb<-0model$ub<-1model$varnames<-paste(rep('El',groundSetSize),1:groundSetSize,sep='')# Build constraint matrixmodel$A<-spMatrix(1,groundSetSize,i=rep(1,groundSetSize),j=1:groundSetSize,x=rep(1,groundSetSize))model$rhs<-c(Budget)model$sense<-c('<')model$constrnames<-c('Budget')# Set multi-objectivesmodel$multiobj<-list()for(min1:nSubSets){model$multiobj[[m]]<-list()model$multiobj[[m]]$objn<-Set[[m]]model$multiobj[[m]]$priority<-SetObjPriority[m]model$multiobj[[m]]$weight<-SetObjWeight[m]model$multiobj[[m]]$abstol<-mmodel$multiobj[[m]]$reltol<-0.01model$multiobj[[m]]$name<-sprintf('Set%d',m)model$multiobj[[m]]$con<-0.0}# Save modelgurobi_write(model,'multiobj_R.lp')# Set parametersparams<-list()params$PoolSolutions<-100# Optimizeresult<-gurobi(model,params)# Capture solution informationif(result$status!='OPTIMAL'){cat('Optimization finished with status',result$status,'\n')stop('Stop now\n')}# Print best solutioncat('Selected elements in best solution:\n')for(ein1:groundSetSize){if(result$x[e]<0.9)nextcat(' El',e,sep='')}cat('\n')# Iterate over the best 10 solutionsif('pool'%in%names(result)){solcount<-length(result$pool)cat('Number of solutions found:',solcount,'\n')if(solcount>10){solcount<-10}cat('Objective values for first',solcount,'solutions:\n')for(kin1:solcount){cat('Solution',k,'has objective:',result$pool[[k]]$objval[1],'\n')}}else{solcount<-1cat('Number of solutions found:',solcount,'\n')cat('Solution 1 has objective:',result$objval,'\n')}# Clean uprm(model,params,result)
Help and Feedback