Hide navigation sidebar
Hide table of contents sidebar
Back to top
Toggle table of contents sidebar

# Multiobj Examples

This section includes source code for all of the Gurobi multiobj examples. The same source code can be found in the `examples` directory of the Gurobi 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 128

    int
    main(void)
    {
      GRBenv   *env   = NULL;
      GRBenv   *menv  = NULL;
      GRBmodel *model = NULL;
      int       error = 0;
      int      *cind  = NULL;
      double   *cval  = NULL;
      char      buffer[MAXSTR];
      int e, i, status, nSolutions;
      double objn;

      /* Sample data */
      const int groundSetSize = 20;
      const int nSubsets      = 4;
      const int Budget        = 12;
      double Set[][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 } };
      int    SetObjPriority[] = {3, 2, 2, 1};
      double SetObjWeight[]   = {1.0, 0.25, 1.25, 1.0};

      /* Create environment */
      error = GRBloadenv(&env, "multiobj_c.log");
      if (error) goto QUIT;

      /* Create initial model */
      error = GRBnewmodel(env, &model, "multiobj_c", groundSetSize, NULL,
                          NULL, NULL, NULL, NULL);
      if (error) goto QUIT;

      /* 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) goto QUIT;

        error = GRBsetstrattrelement(model, "VarName", e, buffer);
        if (error) goto QUIT;
      }

      /* Make space for constraint data */
      cind = malloc(sizeof(int) * groundSetSize);
      if (!cind) goto QUIT;
      cval = malloc(sizeof(double) * groundSetSize);
      if (!cval) goto QUIT;

      /* 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) goto QUIT;

      /* Set global sense for ALL objectives */
      error = GRBsetintattr(model, GRB_INT_ATTR_MODELSENSE, GRB_MAXIMIZE);
      if (error) goto QUIT;

      /* Limit how many solutions to collect */
      error = GRBsetintparam(menv, GRB_INT_PAR_POOLSOLUTIONS, 100);
      if (error) goto QUIT;

      /* 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) goto QUIT;
      }

      /* Save problem */
      error = GRBwrite(model, "multiobj_c.lp");
      if (error) goto QUIT;
      error = GRBwrite(model, "multiobj_c.mps");
      if (error) goto QUIT;

      /* Optimize */
      error = GRBoptimize(model);
      if (error) goto QUIT;

      /* Status checking */
      error = GRBgetintattr(model, "Status", &status);
      if (error) goto QUIT;

      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");
        goto QUIT;
      }
      if (status != GRB_OPTIMAL) {
        printf("Optimization was stopped with status %i\n", status);
        goto QUIT;
      }

      /* Print best selected set */
      error = GRBgetdblattrarray(model, GRB_DBL_ATTR_X, 0, groundSetSize, cval);
      if (error) goto QUIT;

      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) goto QUIT;
      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) goto QUIT;

        printf("\tSet %d:", i);
        for (e = 0; e < nSolutions; e++) {
          error = GRBsetintparam(menv, GRB_INT_PAR_SOLUTIONNUMBER, e);
          if (error) goto QUIT;

          error = GRBgetdblattr(model, GRB_DBL_ATTR_OBJNVAL, &objn);
          if (error) goto QUIT;

          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);

      return error;
    }

    /* 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>
    using namespace std;

    int
    main(void)
    {
      GRBEnv *env  = 0;
      GRBVar *Elem = 0;
      int e, i, status, nSolutions;

      try{
        // Sample data
        const int groundSetSize = 20;
        const int nSubsets      = 4;
        const int Budget        = 12;
        double Set[][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 } };
        int    SetObjPriority[] = {3, 2, 2, 1};
        double SetObjWeight[]   = {1.0, 0.25, 1.25, 1.0};

        // Create environment
        env = new GRBEnv("multiobj_c++.log");

        // Create initial model
        GRBModel model = 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++) {
          ostringstream vname;
          vname << "El" << e;
          Elem[e].set(GRB_StringAttr_VarName, vname.str());
        }

        // Constraint: limit total number of elements to be picked to be at most
        // Budget
        GRBLinExpr lhs;
        lhs = 0;
        for (e = 0; e < groundSetSize; e++) {
          lhs += Elem[e];
        }
        model.addConstr(lhs <= Budget, "Budget");

        // Set global sense for ALL objectives
        model.set(GRB_IntAttr_ModelSense, GRB_MAXIMIZE);

        // Limit how many solutions to collect
        model.set(GRB_IntParam_PoolSolutions, 100);

        // Set and configure i-th objective
        for (i = 0; i < nSubsets; i++) {
          GRBLinExpr objn = 0;
          for (e = 0; e < groundSetSize; e++)
            objn += Set[i][e]*Elem[e];
          ostringstream vname;
          vname << "Set" << i;

          model.setObjectiveN(objn, i, SetObjPriority[i], SetObjWeight[i],
                              1.0 + i, 0.01, vname.str());
        }

        // Save problem
        model.write("multiobj_c++.lp");

        // Optimize
        model.optimize();

        // Status checking
        status = 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;
          return 1;
        }
        if (status != GRB_OPTIMAL) {
          cout << "Optimization was stopped with status " << status << endl;
          return 1;
        }

        // Print best selected set
        cout << "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 stored
        nSolutions = model.get(GRB_IntAttr_SolCount);
        cout << "Number of solutions found: " << nSolutions << endl;

        // Print objective values of solutions
        if (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);
            double val = model.get(GRB_DoubleAttr_ObjNVal);
            cout << std::setw(6) << val;
          }
          cout << endl;
        }

      }
      catch (GRBException e) {
        cout << "Error code = " << e.getErrorCode() << endl;
        cout << e.getMessage() << endl;
      }
      catch (...) {
        cout << "Exception during optimization" << endl;
      }

      // Free environment/vars
      delete[] Elem;
      delete env;
      return 0;
    }

    /* 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. */

    using System;
    using Gurobi;

    class multiobj_cs {
      static void Main() {

        try {
          // Sample data
          int groundSetSize = 20;
          int nSubsets      = 4;
          int Budget        = 12;
          double[,] Set = new double[,]
          { { 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 = new int[] {3, 2, 2, 1};
          double[] SetObjWeight   = new double[] {1.0, 0.25, 1.25, 1.0};
          int e, i, status, nSolutions;

          // Create environment
          GRBEnv env = new GRBEnv("multiobj_cs.log");

          // Create initial model
          GRBModel model = new GRBModel(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++) {
            string vname = string.Format("El{0}", e);
            Elem[e].VarName = vname;
          }

          // Constraint: limit total number of elements to be picked to be at most
          // Budget
          GRBLinExpr lhs = new GRBLinExpr();
          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 objectives
          model.ModelSense = GRB.MAXIMIZE;

          // Limit how many solutions to collect
          model.Parameters.PoolSolutions = 100;

          // Set and configure i-th objective
          for (i = 0; i < nSubsets; i++) {
            string vname = string.Format("Set{0}", i);
            GRBLinExpr objn = new GRBLinExpr();
            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 problem
          model.Write("multiobj_cs.lp");

          // Optimize
          model.Optimize();

          // Status checking
          status = 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 set
          Console.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 stored
          nSolutions = model.SolCount;
          Console.WriteLine("Number of solutions found: {0}", nSolutions);

          // Print objective values of solutions
          if (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 (GRBException e) {
          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. */

    import com.gurobi.gurobi.*;

    public class Multiobj {
      public static void main(String[] args) {

        try {
          // Sample data
          int groundSetSize = 20;
          int nSubsets      = 4;
          int Budget        = 12;
          double Set[][] = new double[][]
          { { 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[] = new int[] {3, 2, 2, 1};
          double SetObjWeight[]   = new double[] {1.0, 0.25, 1.25, 1.0};
          int e, i, status, nSolutions;

          // Create environment
          GRBEnv env = new GRBEnv("Multiobj.log");

          // Create initial model
          GRBModel model = new GRBModel(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++) {
            String vname = "El" + String.valueOf(e);
            Elem[e].set(GRB.StringAttr.VarName, vname);
          }

          // Constraint: limit total number of elements to be picked to be at most
          // Budget
          GRBLinExpr lhs = new GRBLinExpr();
          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 objectives
          model.set(GRB.IntAttr.ModelSense, GRB.MAXIMIZE);

          // Limit how many solutions to collect
          model.set(GRB.IntParam.PoolSolutions, 100);

          // Set and configure i-th objective
          for (i = 0; i < nSubsets; i++) {
            GRBLinExpr objn = new GRBLinExpr();
            String vname = "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 problem
          model.write("Multiobj.lp");

          // Optimize
          model.optimize();

          // Status checking
          status = 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 set
          System.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 stored
          nSolutions = model.get(GRB.IntAttr.SolCount);
          System.out.println("Number of solutions found: " + nSolutions);

          // Print objective values of solutions
          if (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);
              double val = model.get(GRB.DoubleAttr.ObjNVal);
              System.out.print("      " + val);
            }
            System.out.println();
          }
          model.dispose();
          env.dispose();
        } catch (GRBException e) {
          System.out.println("Error code = " + e.getErrorCode());
          System.out.println(e.getMessage());
        }
      }
    }

    function multiobj()

    % 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 data
    groundSetSize     = 20;
    nSubSets          = 4;
    Budget            = 12;
    Set               = [
        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];

    % Initialize model
    model.modelsense  = 'max';
    model.modelname   = 'multiobj';

    % Set variables and constraints
    model.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'};

    for j = 1:groundSetSize
        model.varnames{j} = sprintf('El%d', j);
        model.A(1, j)     = 1;
    end

    % Set multi-objectives
    for m = 1:nSubSets
        model.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 model
    gurobi_write(model,'multiobj_m.lp')

    % Set parameters
    params.PoolSolutions = 100;

    % Optimize
    result = gurobi(model, params);

    % Capture solution information
    if ~strcmp(result.status, 'OPTIMAL')
        fprintf('Optimization finished with status %d, quit now\n', result.status);
        return;
    end

    % Print best solution
    fprintf('Selected elements in best solution:\n');
    for j = 1:groundSetSize
        if result.x(j) >= 0.9
            fprintf('%s ', model.varnames{j});
        end
    end
    fprintf('\n');

    % Print all solution objectives and best furth solution
    if isfield(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);
        for m = 1:nSubSets
            fprintf('  %s:', model.multiobj(m).name);
            for k = 1:solcount
                fprintf('  %3g', result.pool(k).objval(m));
            end
            fprintf('\n');
        end
        fprintf('\n');
    else
        fprintf('Number of solutions found: 1\n');
        fprintf('Solution 1 has objective values:');
        for k = 1:nSubSets
            fprintf('  %g', result.objval(k));
        end
        fprintf('\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.

    import gurobipy as gp
    from gurobipy import GRB
    import sys

    try:
        # Sample data
        Groundset = range(20)
        Subsets = range(4)
        Budget = 12
        Set = [
            [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 model
        model = 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
        # Budget
        model.addConstr(Elem.sum() <= Budget, 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(f"Optimization was stopped with status {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(f"El{e}" for e in selected))

        # Print number of solutions stored
        nSolutions = model.SolCount
        print(f"Number of solutions found: {nSolutions}")

        # Print objective values of solutions
        if nSolutions > 10:
            nSolutions = 10
        print(f"Objective values for first {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(f"\tSet{i}" + "".join(f" {objval:6g}" for objval in objvals[:3]))

    except gp.GurobiError as e:
        print(f"Error code {e.errno}: {e}")

    except AttributeError as e:
        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 data
    groundSetSize     <- 20
    nSubSets          <- 4
    Budget            <- 12
    Set               <- 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 model
    model             <- list()
    model$modelsense  <- 'max'
    model$modelname   <- 'multiobj'

    # Set variables, all of them are binary, with 0,1 bounds.
    model$vtype       <- 'B'
    model$lb          <- 0
    model$ub          <- 1
    model$varnames    <- paste(rep('El', groundSetSize), 1:groundSetSize, sep='')

    # Build constraint matrix
    model$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-objectives
    model$multiobj          <- list()
    for (m in 1: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   <- m
      model$multiobj[[m]]$reltol   <- 0.01
      model$multiobj[[m]]$name     <- sprintf('Set%d', m)
      model$multiobj[[m]]$con      <- 0.0
    }

    # Save model
    gurobi_write(model,'multiobj_R.lp')

    # Set parameters
    params               <- list()
    params$PoolSolutions <- 100

    # Optimize
    result <- gurobi(model, params)

    # Capture solution information
    if (result$status != 'OPTIMAL') {
      cat('Optimization finished with status', result$status, '\n')
      stop('Stop now\n')
    }

    # Print best solution
    cat('Selected elements in best solution:\n')
    for (e in 1:groundSetSize) {
      if(result$x[e] < 0.9) next
      cat(' El',e,sep='')
    }
    cat('\n')

    # Iterate over the best 10 solutions
    if ('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 (k in 1:solcount) {
        cat('Solution', k, 'has objective:', result$pool[[k]]$objval[1], '\n')
      }
    } else {
      solcount <- 1
      cat('Number of solutions found:', solcount, '\n')
      cat('Solution 1 has objective:', result$objval, '\n')
    }

    # Clean up
    rm(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.

    Imports Gurobi

    Class multiobj_vb

        Shared Sub Main()

            Try
                ' Sample data
                Dim groundSetSize As Integer = 20
                Dim nSubsets As Integer = 4
                Dim Budget As Integer = 12

                Dim [Set] As Double(,) = New Double(,) { _
                    {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}}

                Dim SetObjPriority As Integer() = New Integer() {3, 2, 2, 1}
                Dim SetObjWeight As Double() = New Double() {1.0, 0.25, 1.25, 1.0}
                Dim e As Integer, i As Integer, status As Integer, nSolutions As Integer

                ' Create environment
                Dim env As New GRBEnv("multiobj_vb.log")

                ' Create initial model
                Dim model As New GRBModel(env)
                model.ModelName = "multiobj_vb"

                ' Initialize decision variables for ground set:
                ' x[e] == 1 if element e is chosen for the covering.
                Dim Elem As GRBVar() = model.AddVars(groundSetSize, GRB.BINARY)
                For e = 0 To groundSetSize - 1
                    Dim vname As String = "El" & e.ToString()
                    Elem(e).VarName = vname
                Next

                ' Constraint: limit total number of elements to be picked to be at most
                ' Budget
                Dim lhs As New GRBLinExpr()
                For e = 0 To groundSetSize - 1
                    lhs.AddTerm(1.0, Elem(e))
                Next
                model.AddConstr(lhs, GRB.LESS_EQUAL, Budget, "Budget")

                ' Set global sense for ALL objectives
                model.ModelSense = GRB.MAXIMIZE

                ' Limit how many solutions to collect
                model.Parameters.PoolSolutions = 100

                ' Set and configure i-th objective
                For i = 0 To nSubsets - 1
                    Dim vname As String = String.Format("Set{0}", i)
                    Dim objn As New GRBLinExpr()
                    For e = 0 To groundSetSize - 1
                        objn.AddTerm([Set](i, e), Elem(e))
                    Next

                    model.SetObjectiveN(objn, i, SetObjPriority(i), SetObjWeight(i), _
                                        1.0 + i, 0.01, vname)
                Next

                ' Save problem
                model.Write("multiobj_vb.lp")

                ' Optimize
                model.Optimize()

                ' Status checking
                status = model.Status

                If status = GRB.Status.INF_OR_UNBD OrElse _
                   status = GRB.Status.INFEASIBLE OrElse _
                   status = GRB.Status.UNBOUNDED Then
                    Console.WriteLine("The model cannot be solved " & _
                             "because it is infeasible or unbounded")
                    Return
                End If
                If status <> GRB.Status.OPTIMAL Then
                    Console.WriteLine("Optimization was stopped with status {0}", status)
                    Return
                End If

                ' Print best selected set
                Console.WriteLine("Selected elements in best solution:")
                Console.Write(vbTab)
                For e = 0 To groundSetSize - 1
                    If Elem(e).X < 0.9 Then
                        Continue For
                    End If
                    Console.Write("El{0} ", e)
                Next
                Console.WriteLine()

                ' Print number of solutions stored
                nSolutions = model.SolCount
                Console.WriteLine("Number of solutions found: {0}", nSolutions)

                ' Print objective values of solutions
                If nSolutions > 10 Then
                    nSolutions = 10
                End If
                Console.WriteLine("Objective values for first {0} solutions:", nSolutions)
                For i = 0 To nSubsets - 1
                    model.Parameters.ObjNumber = i

                    Console.Write(vbTab & "Set" & i)
                    For e = 0 To nSolutions - 1
                        model.Parameters.SolutionNumber = e
                        Console.Write("{0,8}", model.ObjNVal)
                    Next
                    Console.WriteLine()
                Next

                model.Dispose()
                env.Dispose()

            Catch e As GRBException
                Console.WriteLine("Error code = {0}", e)
                Console.WriteLine(e.Message)

            End Try
        End Sub
    End Class

Help and Feedback

Press `/` or click to search this documentation | Gurobi website | Gurobi community forum
Go to other Gurobi documentation | Gurobi download | Contact support