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

# Lp Examples

This section includes source code for all of the Gurobi lp examples. The same source code can be found in the `examples` directory of the Gurobi distribution.

    /* Copyright 2025, Gurobi Optimization, LLC */

    /* This example reads an LP model from a file and solves it.
       If the model is infeasible or unbounded, the example turns off
       presolve and solves the model again. If the model is infeasible,
       the example computes an Irreducible Inconsistent Subsystem (IIS),
       and writes it to a file */

    #include <stdlib.h>
    #include <stdio.h>
    #include <math.h>
    #include "gurobi_c.h"

    int
    main(int   argc,
         char *argv[])
    {
      GRBenv   *env   = NULL;
      GRBmodel *model = NULL;
      int       error = 0;
      int       optimstatus;
      double    objval;

      if (argc < 2) {
        fprintf(stderr, "Usage: lp_c filename\n");
        exit(1);
      }

      /* Create environment */

      error = GRBloadenv(&env, "lp.log");
      if (error) goto QUIT;

      /* Read model from file */

      error = GRBreadmodel(env, argv[1], &model);
      if (error) goto QUIT;

      /* Solve model */

      error = GRBoptimize(model);
      if (error) goto QUIT;

      /* Capture solution information */

      error = GRBgetintattr(model, GRB_INT_ATTR_STATUS, &optimstatus);
      if (error) goto QUIT;

      /* If model is infeasible or unbounded, turn off presolve and resolve */

      if (optimstatus == GRB_INF_OR_UNBD) {
        /* Change parameter on model environment.  The model now has
           a copy of the original environment, so changing the original will
           no longer affect the model.  */

        error = GRBsetintparam(GRBgetenv(model), "PRESOLVE", 0);
        if (error) goto QUIT;

        error = GRBoptimize(model);
        if (error) goto QUIT;

        error = GRBgetintattr(model, GRB_INT_ATTR_STATUS, &optimstatus);
        if (error) goto QUIT;
      }

      if (optimstatus == GRB_OPTIMAL) {
        error = GRBgetdblattr(model, GRB_DBL_ATTR_OBJVAL, &objval);
        if (error) goto QUIT;
        printf("Optimal objective: %.4e\n\n", objval);
      } else if (optimstatus == GRB_INFEASIBLE) {
        printf("Model is infeasible\n\n");

        error = GRBcomputeIIS(model);
        if (error) goto QUIT;

        error = GRBwrite(model, "model.ilp");
        if (error) goto QUIT;
      } else if (optimstatus == GRB_UNBOUNDED) {
        printf("Model is unbounded\n\n");
      } else {
        printf("Optimization was stopped with status = %d\n\n", optimstatus);
      }

    QUIT:

      /* Error reporting */

      if (error) {
        printf("ERROR: %s\n", GRBgeterrormsg(env));
        exit(1);
      }

      /* Free model */

      GRBfreemodel(model);

      /* Free environment */

      GRBfreeenv(env);

      return 0;
    }

    /* Copyright 2025, Gurobi Optimization, LLC */

    /* This example reads an LP model from a file and solves it.
       If the model is infeasible or unbounded, the example turns off
       presolve and solves the model again. If the model is infeasible,
       the example computes an Irreducible Inconsistent Subsystem (IIS),
       and writes it to a file */

    #include "gurobi_c++.h"
    using namespace std;

    int
    main(int   argc,
         char *argv[])
    {
      if (argc < 2) {
        cout << "Usage: lp_c++ filename" << endl;
        return 1;
      }

      try {
        GRBEnv env = GRBEnv();
        GRBModel model = GRBModel(env, argv[1]);

        model.optimize();

        int optimstatus = model.get(GRB_IntAttr_Status);

        if (optimstatus == GRB_INF_OR_UNBD) {
          model.set(GRB_IntParam_Presolve, 0);
          model.optimize();
          optimstatus = model.get(GRB_IntAttr_Status);
        }

        if (optimstatus == GRB_OPTIMAL) {
          double objval = model.get(GRB_DoubleAttr_ObjVal);
          cout << "Optimal objective: " << objval << endl;
        } else if (optimstatus == GRB_INFEASIBLE) {
          cout << "Model is infeasible" << endl;

          // compute and write out IIS

          model.computeIIS();
          model.write("model.ilp");
        } else if (optimstatus == GRB_UNBOUNDED) {
          cout << "Model is unbounded" << endl;
        } else {
          cout << "Optimization was stopped with status = "
               << optimstatus << endl;
        }

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

      return 0;
    }

    /* Copyright 2025, Gurobi Optimization, LLC */

    /* This example reads an LP model from a file and solves it.
       If the model is infeasible or unbounded, the example turns off
       presolve and solves the model again. If the model is infeasible,
       the example computes an Irreducible Inconsistent Subsystem (IIS),
       and writes it to a file. */

    using System;
    using Gurobi;

    class lp_cs
    {
      static void Main(string[] args)
      {
        if (args.Length < 1) {
          Console.Out.WriteLine("Usage: lp_cs filename");
          return;
        }

        try {
          GRBEnv env = new GRBEnv();
          GRBModel model = new GRBModel(env, args[0]);

          model.Optimize();

          int optimstatus = model.Status;

          if (optimstatus == GRB.Status.INF_OR_UNBD) {
            model.Parameters.Presolve = 0;
            model.Optimize();
            optimstatus = model.Status;
          }

          if (optimstatus == GRB.Status.OPTIMAL) {
            double objval = model.ObjVal;
            Console.WriteLine("Optimal objective: " + objval);
          } else if (optimstatus == GRB.Status.INFEASIBLE) {
            Console.WriteLine("Model is infeasible");

            // compute and write out IIS

            model.ComputeIIS();
            model.Write("model.ilp");
          } else if (optimstatus == GRB.Status.UNBOUNDED) {
            Console.WriteLine("Model is unbounded");
          } else {
            Console.WriteLine("Optimization was stopped with status = "
                               + optimstatus);
          }

          // Dispose of model and env
          model.Dispose();
          env.Dispose();

        } catch (GRBException e) {
          Console.WriteLine("Error code: " + e.ErrorCode + ". " + e.Message);
        }
      }
    }

    /* Copyright 2025, Gurobi Optimization, LLC */

    /* This example reads an LP model from a file and solves it.
       If the model is infeasible or unbounded, the example turns off
       presolve and solves the model again. If the model is infeasible,
       the example computes an Irreducible Inconsistent Subsystem (IIS),
       and writes it to a file */

    import com.gurobi.gurobi.*;

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

        if (args.length < 1) {
          System.out.println("Usage: java Lp filename");
          System.exit(1);
        }

        try {
          GRBEnv env = new GRBEnv();
          GRBModel model = new GRBModel(env, args[0]);

          model.optimize();

          int optimstatus = model.get(GRB.IntAttr.Status);

          if (optimstatus == GRB.Status.INF_OR_UNBD) {
            model.set(GRB.IntParam.Presolve, 0);
            model.optimize();
            optimstatus = model.get(GRB.IntAttr.Status);
          }

          if (optimstatus == GRB.Status.OPTIMAL) {
            double objval = model.get(GRB.DoubleAttr.ObjVal);
            System.out.println("Optimal objective: " + objval);
          } else if (optimstatus == GRB.Status.INFEASIBLE) {
            System.out.println("Model is infeasible");

            // Compute and write out IIS
            model.computeIIS();
            model.write("model.ilp");
          } else if (optimstatus == GRB.Status.UNBOUNDED) {
            System.out.println("Model is unbounded");
          } else {
            System.out.println("Optimization was stopped with status = "
                               + optimstatus);
          }

          // Dispose of model and environment
          model.dispose();
          env.dispose();

        } catch (GRBException e) {
          System.out.println("Error code: " + e.getErrorCode() + ". " +
              e.getMessage());
        }
      }
    }

    function lp()
    % Copyright 2025, Gurobi Optimization, LLC
    %
    % This example formulates and solves the following simple LP model:
    % maximize
    %       x + 2 y + 3 z
    % subject to
    %       x +   y        <= 1
    %             y +   z  <= 1
    %

    model.A = sparse([1 1 0; 0 1 1]);
    model.obj = [1 2 3];
    model.modelsense = 'Max';
    model.rhs = [1 1];
    model.sense = [ '<' '<'];

    result = gurobi(model);

    disp(result.objval);
    disp(result.x);

    % Alterantive representation of A - as sparse triplet matrix
    i = [1; 1; 2; 2];
    j = [1; 2; 2; 3];
    x = [1; 1; 1; 1];
    model.A = sparse(i, j, x, 2, 3);

    % Set some parameters
    params.method = 2;
    params.timelimit = 100;

    result = gurobi(model, params);

    disp(result.objval);
    disp(result.x)
    end

    #!/usr/bin/env python3

    # Copyright 2025, Gurobi Optimization, LLC

    # This example reads an LP model from a file and solves it.
    # If the model is infeasible or unbounded, the example turns off
    # presolve and solves the model again. If the model is infeasible,
    # the example computes an Irreducible Inconsistent Subsystem (IIS),
    # and writes it to a file

    import sys
    import gurobipy as gp
    from gurobipy import GRB

    if len(sys.argv) < 2:
        print("Usage: lp.py filename")
        sys.exit(0)

    # Read and solve model

    model = gp.read(sys.argv[1])
    model.optimize()

    if model.Status == GRB.INF_OR_UNBD:
        # Turn presolve off to determine whether model is infeasible
        # or unbounded
        model.setParam(GRB.Param.Presolve, 0)
        model.optimize()

    if model.Status == GRB.OPTIMAL:
        print(f"Optimal objective: {model.ObjVal:g}")
        model.write("model.sol")
        sys.exit(0)
    elif model.Status != GRB.INFEASIBLE:
        print(f"Optimization was stopped with status {model.Status}")
        sys.exit(0)

    # Model is infeasible - compute an Irreducible Inconsistent Subsystem (IIS)

    print("")
    print("Model is infeasible")
    model.computeIIS()
    model.write("model.ilp")
    print("IIS written to file 'model.ilp'")

    # Copyright 2025, Gurobi Optimization, LLC
    #
    # This example formulates and solves the following simple LP model:
    #  maximize
    #        x + 2 y + 3 z
    #  subject to
    #        x +   y       <= 1
    #              y +   z <= 1

    library(Matrix)
    library(gurobi)

    model <- list()

    model$A          <- matrix(c(1,1,0,0,1,1), nrow=2, byrow=T)
    model$obj        <- c(1,2,3)
    model$modelsense <- 'max'
    model$rhs        <- c(1,1)
    model$sense      <- c('<', '<')

    result <- gurobi(model)

    print(result$objval)
    print(result$x)

    # Second option for A - as a sparseMatrix (using the Matrix package)...

    model$A <- spMatrix(2, 3, c(1, 1, 2, 2), c(1, 2, 2, 3), c(1, 1, 1, 1))

    params <- list(Method=2, TimeLimit=100)

    result <- gurobi(model, params)

    print(result$objval)
    print(result$x)

    # Third option for A - as a sparse triplet matrix (using the slam package)...

    model$A <- simple_triplet_matrix(c(1, 1, 2, 2), c(1, 2, 2, 3), c(1, 1, 1, 1))

    params <- list(Method=2, TimeLimit=100)

    result <- gurobi(model, params)

    print(result$objval)
    print(result$x)

    # Clear space
    rm(result, params, model)

    ' Copyright 2025, Gurobi Optimization, LLC
    '
    ' This example reads an LP model from a file and solves it.
    ' If the model is infeasible or unbounded, the example turns off
    ' presolve and solves the model again. If the model is infeasible,
    ' the example computes an Irreducible Inconsistent Subsystem (IIS),
    ' and writes it to a file.

    Imports System
    Imports Gurobi

    Class lp_vb
        Shared Sub Main(ByVal args As String())

            If args.Length < 1 Then
                Console.WriteLine("Usage: lp_vb filename")
                Return
            End If

            Try
                Dim env As GRBEnv = New GRBEnv("lp1.log")
                Dim model As GRBModel = New GRBModel(env, args(0))

                model.Optimize()

                Dim optimstatus As Integer = model.Status

                If optimstatus = GRB.Status.INF_OR_UNBD Then
                    model.Parameters.Presolve = 0
                    model.Optimize()
                    optimstatus = model.Status
                End If

                If optimstatus = GRB.Status.OPTIMAL Then
                    Dim objval As Double = model.ObjVal
                    Console.WriteLine("Optimal objective: " & objval)
                ElseIf optimstatus = GRB.Status.INFEASIBLE Then
                    Console.WriteLine("Model is infeasible")
                    model.ComputeIIS()
                    model.Write("model.ilp")
                ElseIf optimstatus = GRB.Status.UNBOUNDED Then
                    Console.WriteLine("Model is unbounded")
                Else
                    Console.WriteLine("Optimization was stopped with status = " & _
                                      optimstatus)
                End If

                ' Dispose of model and env
                model.Dispose()
                env.Dispose()

            Catch e As GRBException
                Console.WriteLine("Error code: " & e.ErrorCode & ". " & 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