This section includes source code for all of the Gurobi multiobj examples.The same source code can be found in theexamples directory of theGurobi distribution.
/* 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. */#include<assert.h>#include<stdlib.h>#include<stdio.h>#include<math.h>#include<string.h>#include"gurobi_c.h"#define MAXSTR 128intmain(void){GRBenv*env=NULL;GRBenv*menv=NULL;GRBmodel*model=NULL;interror=0;int*cind=NULL;double*cval=NULL;charbuffer[MAXSTR];inte,i,status,nSolutions;doubleobjn;/* Sample data */constintgroundSetSize=20;constintnSubsets=4;constintBudget=12;doubleSet[][20]={{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}};intSetObjPriority[]={3,2,2,1};doubleSetObjWeight[]={1.0,0.25,1.25,1.0};/* Create environment */error=GRBloadenv(&env,"multiobj_c.log");if(error)gotoQUIT;/* Create initial model */error=GRBnewmodel(env,&model,"multiobj_c",groundSetSize,NULL,NULL,NULL,NULL,NULL);if(error)gotoQUIT;/* get model environment */menv=GRBgetenv(model);assert(menv!=NULL);/* Initialize decision variables for ground set: * x[e] == 1 if element e is chosen for the covering. */for(e=0;e<groundSetSize;e++){sprintf(buffer,"El%d",e);error=GRBsetcharattrelement(model,"VType",e,GRB_BINARY);if(error)gotoQUIT;error=GRBsetstrattrelement(model,"VarName",e,buffer);if(error)gotoQUIT;}/* Make space for constraint data */cind=malloc(sizeof(int)*groundSetSize);if(!cind)gotoQUIT;cval=malloc(sizeof(double)*groundSetSize);if(!cval)gotoQUIT;/* Constraint: limit total number of elements to be picked to be at most * Budget */for(e=0;e<groundSetSize;e++){cind[e]=e;cval[e]=1.0;}sprintf(buffer,"Budget");error=GRBaddconstr(model,groundSetSize,cind,cval,GRB_LESS_EQUAL,(double)Budget,buffer);if(error)gotoQUIT;/* Set global sense for ALL objectives */error=GRBsetintattr(model,GRB_INT_ATTR_MODELSENSE,GRB_MAXIMIZE);if(error)gotoQUIT;/* Limit how many solutions to collect */error=GRBsetintparam(menv,GRB_INT_PAR_POOLSOLUTIONS,100);if(error)gotoQUIT;/* Set and configure i-th objective */for(i=0;i<nSubsets;i++){sprintf(buffer,"Set%d",i+1);error=GRBsetobjectiven(model,i,SetObjPriority[i],SetObjWeight[i],1.0+i,0.01,buffer,0.0,groundSetSize,cind,Set[i]);if(error)gotoQUIT;}/* Save problem */error=GRBwrite(model,"multiobj_c.lp");if(error)gotoQUIT;error=GRBwrite(model,"multiobj_c.mps");if(error)gotoQUIT;/* Optimize */error=GRBoptimize(model);if(error)gotoQUIT;/* Status checking */error=GRBgetintattr(model,"Status",&status);if(error)gotoQUIT;if(status==GRB_INF_OR_UNBD||status==GRB_INFEASIBLE||status==GRB_UNBOUNDED){printf("The model cannot be solved ""because it is infeasible or unbounded\n");gotoQUIT;}if(status!=GRB_OPTIMAL){printf("Optimization was stopped with status %i\n",status);gotoQUIT;}/* Print best selected set */error=GRBgetdblattrarray(model,GRB_DBL_ATTR_X,0,groundSetSize,cval);if(error)gotoQUIT;printf("Selected elements in best solution:\n\t");for(e=0;e<groundSetSize;e++){if(cval[e]<.9)continue;printf("El%d ",e);}/* Print number of solutions stored */error=GRBgetintattr(model,GRB_INT_ATTR_SOLCOUNT,&nSolutions);if(error)gotoQUIT;printf("\nNumber of solutions found: %d\n",nSolutions);/* Print objective values of solutions */if(nSolutions>10)nSolutions=10;printf("Objective values for first %d solutions:\n",nSolutions);for(i=0;i<nSubsets;i++){error=GRBsetintparam(menv,GRB_INT_PAR_OBJNUMBER,i);if(error)gotoQUIT;printf("\tSet %d:",i);for(e=0;e<nSolutions;e++){error=GRBsetintparam(menv,GRB_INT_PAR_SOLUTIONNUMBER,e);if(error)gotoQUIT;error=GRBgetdblattr(model,GRB_DBL_ATTR_OBJNVAL,&objn);if(error)gotoQUIT;printf(" %6g",objn);}printf("\n");}QUIT:if(cind!=NULL)free(cind);if(cval!=NULL)free(cval);if(model!=NULL)GRBfreemodel(model);if(env!=NULL)GRBfreeenv(env);returnerror;}
/* 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. */#include"gurobi_c++.h"#include<sstream>#include<iomanip>usingnamespacestd;intmain(void){GRBEnv*env=0;GRBVar*Elem=0;inte,i,status,nSolutions;try{// Sample dataconstintgroundSetSize=20;constintnSubsets=4;constintBudget=12;doubleSet[][20]={{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}};intSetObjPriority[]={3,2,2,1};doubleSetObjWeight[]={1.0,0.25,1.25,1.0};// Create environmentenv=newGRBEnv("multiobj_c++.log");// Create initial modelGRBModelmodel=GRBModel(*env);model.set(GRB_StringAttr_ModelName,"multiobj_c++");// Initialize decision variables for ground set:// x[e] == 1 if element e is chosen for the covering.Elem=model.addVars(groundSetSize,GRB_BINARY);for(e=0;e<groundSetSize;e++){ostringstreamvname;vname<<"El"<<e;Elem[e].set(GRB_StringAttr_VarName,vname.str());}// Constraint: limit total number of elements to be picked to be at most// BudgetGRBLinExprlhs;lhs=0;for(e=0;e<groundSetSize;e++){lhs+=Elem[e];}model.addConstr(lhs<=Budget,"Budget");// Set global sense for ALL objectivesmodel.set(GRB_IntAttr_ModelSense,GRB_MAXIMIZE);// Limit how many solutions to collectmodel.set(GRB_IntParam_PoolSolutions,100);// Set and configure i-th objectivefor(i=0;i<nSubsets;i++){GRBLinExprobjn=0;for(e=0;e<groundSetSize;e++)objn+=Set[i][e]*Elem[e];ostringstreamvname;vname<<"Set"<<i;model.setObjectiveN(objn,i,SetObjPriority[i],SetObjWeight[i],1.0+i,0.01,vname.str());}// Save problemmodel.write("multiobj_c++.lp");// Optimizemodel.optimize();// Status checkingstatus=model.get(GRB_IntAttr_Status);if(status==GRB_INF_OR_UNBD||status==GRB_INFEASIBLE||status==GRB_UNBOUNDED){cout<<"The model cannot be solved "<<"because it is infeasible or unbounded"<<endl;return1;}if(status!=GRB_OPTIMAL){cout<<"Optimization was stopped with status "<<status<<endl;return1;}// Print best selected setcout<<"Selected elements in best solution:"<<endl<<"\t";for(e=0;e<groundSetSize;e++){if(Elem[e].get(GRB_DoubleAttr_X)<.9)continue;cout<<" El"<<e;}cout<<endl;// Print number of solutions storednSolutions=model.get(GRB_IntAttr_SolCount);cout<<"Number of solutions found: "<<nSolutions<<endl;// Print objective values of solutionsif(nSolutions>10)nSolutions=10;cout<<"Objective values for first "<<nSolutions;cout<<" solutions:"<<endl;for(i=0;i<nSubsets;i++){model.set(GRB_IntParam_ObjNumber,i);cout<<"\tSet"<<i;for(e=0;e<nSolutions;e++){cout<<" ";model.set(GRB_IntParam_SolutionNumber,e);doubleval=model.get(GRB_DoubleAttr_ObjNVal);cout<<std::setw(6)<<val;}cout<<endl;}}catch(GRBExceptione){cout<<"Error code = "<<e.getErrorCode()<<endl;cout<<e.getMessage()<<endl;}catch(...){cout<<"Exception during optimization"<<endl;}// Free environment/varsdelete[]Elem;deleteenv;return0;}
/* 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. */usingSystem;usingGurobi;classmultiobj_cs{staticvoidMain(){try{// Sample dataintgroundSetSize=20;intnSubsets=4;intBudget=12;double[,]Set=newdouble[,]{{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}};int[]SetObjPriority=newint[]{3,2,2,1};double[]SetObjWeight=newdouble[]{1.0,0.25,1.25,1.0};inte,i,status,nSolutions;// Create environmentGRBEnvenv=newGRBEnv("multiobj_cs.log");// Create initial modelGRBModelmodel=newGRBModel(env);model.ModelName="multiobj_cs";// Initialize decision variables for ground set:// x[e] == 1 if element e is chosen for the covering.GRBVar[]Elem=model.AddVars(groundSetSize,GRB.BINARY);for(e=0;e<groundSetSize;e++){stringvname=string.Format("El{0}",e);Elem[e].VarName=vname;}// Constraint: limit total number of elements to be picked to be at most// BudgetGRBLinExprlhs=newGRBLinExpr();for(e=0;e<groundSetSize;e++){lhs.AddTerm(1.0,Elem[e]);}model.AddConstr(lhs,GRB.LESS_EQUAL,Budget,"Budget");// Set global sense for ALL objectivesmodel.ModelSense=GRB.MAXIMIZE;// Limit how many solutions to collectmodel.Parameters.PoolSolutions=100;// Set and configure i-th objectivefor(i=0;i<nSubsets;i++){stringvname=string.Format("Set{0}",i);GRBLinExprobjn=newGRBLinExpr();for(e=0;e<groundSetSize;e++){objn.AddTerm(Set[i,e],Elem[e]);}model.SetObjectiveN(objn,i,SetObjPriority[i],SetObjWeight[i],1.0+i,0.01,vname);}// Save problemmodel.Write("multiobj_cs.lp");// Optimizemodel.Optimize();// Status checkingstatus=model.Status;if(status==GRB.Status.INF_OR_UNBD||status==GRB.Status.INFEASIBLE||status==GRB.Status.UNBOUNDED){Console.WriteLine("The model cannot be solved "+"because it is infeasible or unbounded");return;}if(status!=GRB.Status.OPTIMAL){Console.WriteLine("Optimization was stopped with status {0}",status);return;}// Print best selected setConsole.WriteLine("Selected elements in best solution:");Console.Write("\t");for(e=0;e<groundSetSize;e++){if(Elem[e].X<.9)continue;Console.Write("El{0} ",e);}Console.WriteLine();// Print number of solutions storednSolutions=model.SolCount;Console.WriteLine("Number of solutions found: {0}",nSolutions);// Print objective values of solutionsif(nSolutions>10)nSolutions=10;Console.WriteLine("Objective values for first {0} solutions:",nSolutions);for(i=0;i<nSubsets;i++){model.Parameters.ObjNumber=i;Console.Write("\tSet"+i);for(e=0;e<nSolutions;e++){model.Parameters.SolutionNumber=e;Console.Write("{0,8}",model.ObjNVal);}Console.WriteLine();}model.Dispose();env.Dispose();}catch(GRBExceptione){Console.WriteLine("Error code = {0}",e);Console.WriteLine(e.Message);}}}
/* 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. */importcom.gurobi.gurobi.*;publicclassMultiobj{publicstaticvoidmain(String[]args){try{// Sample dataintgroundSetSize=20;intnSubsets=4;intBudget=12;doubleSet[][]=newdouble[][]{{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}};intSetObjPriority[]=newint[]{3,2,2,1};doubleSetObjWeight[]=newdouble[]{1.0,0.25,1.25,1.0};inte,i,status,nSolutions;// Create environmentGRBEnvenv=newGRBEnv("Multiobj.log");// Create initial modelGRBModelmodel=newGRBModel(env);model.set(GRB.StringAttr.ModelName,"Multiobj");// Initialize decision variables for ground set:// x[e] == 1 if element e is chosen for the covering.GRBVar[]Elem=model.addVars(groundSetSize,GRB.BINARY);for(e=0;e<groundSetSize;e++){Stringvname="El"+String.valueOf(e);Elem[e].set(GRB.StringAttr.VarName,vname);}// Constraint: limit total number of elements to be picked to be at most// BudgetGRBLinExprlhs=newGRBLinExpr();for(e=0;e<groundSetSize;e++){lhs.addTerm(1.0,Elem[e]);}model.addConstr(lhs,GRB.LESS_EQUAL,Budget,"Budget");// Set global sense for ALL objectivesmodel.set(GRB.IntAttr.ModelSense,GRB.MAXIMIZE);// Limit how many solutions to collectmodel.set(GRB.IntParam.PoolSolutions,100);// Set and configure i-th objectivefor(i=0;i<nSubsets;i++){GRBLinExprobjn=newGRBLinExpr();Stringvname="Set"+String.valueOf(i);for(e=0;e<groundSetSize;e++)objn.addTerm(Set[i][e],Elem[e]);model.setObjectiveN(objn,i,SetObjPriority[i],SetObjWeight[i],1.0+i,0.01,vname);}// Save problemmodel.write("Multiobj.lp");// Optimizemodel.optimize();// Status checkingstatus=model.get(GRB.IntAttr.Status);if(status==GRB.INF_OR_UNBD||status==GRB.INFEASIBLE||status==GRB.UNBOUNDED){System.out.println("The model cannot be solved "+"because it is infeasible or unbounded");System.exit(1);}if(status!=GRB.OPTIMAL){System.out.println("Optimization was stopped with status "+status);System.exit(1);}// Print best selected setSystem.out.println("Selected elements in best solution:");System.out.println("\t");for(e=0;e<groundSetSize;e++){if(Elem[e].get(GRB.DoubleAttr.X)<.9)continue;System.out.print(" El"+e);}System.out.println();// Print number of solutions storednSolutions=model.get(GRB.IntAttr.SolCount);System.out.println("Number of solutions found: "+nSolutions);// Print objective values of solutionsif(nSolutions>10)nSolutions=10;System.out.println("Objective values for first "+nSolutions);System.out.println(" solutions:");for(i=0;i<nSubsets;i++){model.set(GRB.IntParam.ObjNumber,i);System.out.print("\tSet"+i);for(e=0;e<nSolutions;e++){System.out.print(" ");model.set(GRB.IntParam.SolutionNumber,e);doubleval=model.get(GRB.DoubleAttr.ObjNVal);System.out.print(" "+val);}System.out.println();}model.dispose();env.dispose();}catch(GRBExceptione){System.out.println("Error code = "+e.getErrorCode());System.out.println(e.getMessage());}}}
functionmultiobj()% 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.% define primitive datagroundSetSize=20;nSubSets=4;Budget=12;Set=[11111111110000000000;00000111110000011111;00011011000001101100;00011100011100011100];SetObjPriority=[3;2;2;1];SetObjWeight=[1.0;0.25;1.25;1.0];% Initialize modelmodel.modelsense='max';model.modelname='multiobj';% Set variables and constraintsmodel.vtype=repmat('B',groundSetSize,1);model.lb=zeros(groundSetSize,1);model.ub=ones(groundSetSize,1);model.A=sparse(1,groundSetSize);model.rhs=Budget;model.sense='<';model.constrnames={'Budget'};forj=1:groundSetSizemodel.varnames{j}=sprintf('El%d',j);model.A(1,j)=1;end% Set multi-objectivesform=1:nSubSetsmodel.multiobj(m).objn=Set(m,:);model.multiobj(m).priority=SetObjPriority(m);model.multiobj(m).weight=SetObjWeight(m);model.multiobj(m).abstol=m;model.multiobj(m).reltol=0.01;model.multiobj(m).name=sprintf('Set%d',m);model.multiobj(m).con=0.0;end% Save modelgurobi_write(model,'multiobj_m.lp')% Set parametersparams.PoolSolutions=100;% Optimizeresult=gurobi(model,params);% Capture solution informationif~strcmp(result.status,'OPTIMAL')fprintf('Optimization finished with status %d, quit now\n',result.status);return;end% Print best solutionfprintf('Selected elements in best solution:\n');forj=1:groundSetSizeifresult.x(j)>=0.9fprintf('%s ',model.varnames{j});endendfprintf('\n');% Print all solution objectives and best furth solutionifisfield(result,'pool')&&~isempty(result.pool)solcount=length(result.pool);fprintf('Number of solutions found: %d\n',solcount);fprintf('Objective values for first %d solutions:\n',solcount);form=1:nSubSetsfprintf(' %s:',model.multiobj(m).name);fork=1:solcountfprintf(' %3g',result.pool(k).objval(m));endfprintf('\n');endfprintf('\n');elsefprintf('Number of solutions found: 1\n');fprintf('Solution 1 has objective values:');fork=1:nSubSetsfprintf(' %g',result.objval(k));endfprintf('\n');end
#!/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}")
# 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)
' 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.ImportsGurobiClassmultiobj_vbSharedSubMain()Try' Sample dataDimgroundSetSizeAsInteger=20DimnSubsetsAsInteger=4DimBudgetAsInteger=12Dim[Set]AsDouble(,)=NewDouble(,){_{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}}DimSetObjPriorityAsInteger()=NewInteger(){3,2,2,1}DimSetObjWeightAsDouble()=NewDouble(){1.0,0.25,1.25,1.0}DimeAsInteger,iAsInteger,statusAsInteger,nSolutionsAsInteger' Create environmentDimenvAsNewGRBEnv("multiobj_vb.log")' Create initial modelDimmodelAsNewGRBModel(env)model.ModelName="multiobj_vb"' Initialize decision variables for ground set:' x[e] == 1 if element e is chosen for the covering.DimElemAsGRBVar()=model.AddVars(groundSetSize,GRB.BINARY)Fore=0TogroundSetSize-1DimvnameAsString="El"&e.ToString()Elem(e).VarName=vnameNext' Constraint: limit total number of elements to be picked to be at most' BudgetDimlhsAsNewGRBLinExpr()Fore=0TogroundSetSize-1lhs.AddTerm(1.0,Elem(e))Nextmodel.AddConstr(lhs,GRB.LESS_EQUAL,Budget,"Budget")' Set global sense for ALL objectivesmodel.ModelSense=GRB.MAXIMIZE' Limit how many solutions to collectmodel.Parameters.PoolSolutions=100' Set and configure i-th objectiveFori=0TonSubsets-1DimvnameAsString=String.Format("Set{0}",i)DimobjnAsNewGRBLinExpr()Fore=0TogroundSetSize-1objn.AddTerm([Set](i,e),Elem(e))Nextmodel.SetObjectiveN(objn,i,SetObjPriority(i),SetObjWeight(i),_1.0+i,0.01,vname)Next' Save problemmodel.Write("multiobj_vb.lp")' Optimizemodel.Optimize()' Status checkingstatus=model.StatusIfstatus=GRB.Status.INF_OR_UNBDOrElse_status=GRB.Status.INFEASIBLEOrElse_status=GRB.Status.UNBOUNDEDThenConsole.WriteLine("The model cannot be solved "&_"because it is infeasible or unbounded")ReturnEndIfIfstatus<>GRB.Status.OPTIMALThenConsole.WriteLine("Optimization was stopped with status {0}",status)ReturnEndIf' Print best selected setConsole.WriteLine("Selected elements in best solution:")Console.Write(vbTab)Fore=0TogroundSetSize-1IfElem(e).X<0.9ThenContinueForEndIfConsole.Write("El{0} ",e)NextConsole.WriteLine()' Print number of solutions storednSolutions=model.SolCountConsole.WriteLine("Number of solutions found: {0}",nSolutions)' Print objective values of solutionsIfnSolutions>10ThennSolutions=10EndIfConsole.WriteLine("Objective values for first {0} solutions:",nSolutions)Fori=0TonSubsets-1model.Parameters.ObjNumber=iConsole.Write(vbTab&"Set"&i)Fore=0TonSolutions-1model.Parameters.SolutionNumber=eConsole.Write("{0,8}",model.ObjNVal)NextConsole.WriteLine()Nextmodel.Dispose()env.Dispose()CatcheAsGRBExceptionConsole.WriteLine("Error code = {0}",e)Console.WriteLine(e.Message)EndTryEndSubEndClass
Help and Feedback