Load and solve a model from a file

Examples: batchmode, callback, feasopt, fixanddive, lp, lpmethod, lpmod, mip2, params, sensitivity

One of the most basic tasks you can perform with the Gurobi libraries is to read a model from a file, optimize it, and report the result. The lp (lp_c.c, lp_c++.cpp, lp_cs.cs, Lp.java, lp.py, lp_vb.vb) and mip2 (mip2_c.c, mip2_c++.cpp, mip2_cs.cs, Mip2.java, mip2.m, mip2.py, mip2.R, mip2_vb.vb) examples are simple illustrations of how this is done in the various supported Gurobi languages. While the specifics vary from one language to another, the basic structure remains the same for all languages.

After initializing the Gurobi environment, the examples begin by reading the model from the specified file. In C, you call the GRBreadmodel() function:

  error = GRBreadmodel(env, argv[1], &model);
In C++, this is done by constructing a GRBModel object:
    GRBModel model = GRBModel(env, argv[1]);
In C# and Java, this is also done by constructing a GRBModel object:
      GRBModel model = new GRBModel(env, args[0]);
In Python, this is done via the read global function:
model = gp.read(sys.argv[1])

The next step is to invoke the Gurobi optimizer on the model. In C, you call GRBoptimize() on the model variable:

  error = GRBoptimize(model);
In C++, Java, and Python, this is accomplished by calling the optimize method on the model object:
In C#, the first letter of the method name is capitalized:
A successful optimize call populates a set of solution attributes in the model. For example, once the call completes, the X variable attribute contains the solution value for each variable. Similarly, for continuous models, the Pi constraint attribute contains the dual value for each constraint.

The examples then retrieve the value of the model Status attribute to determine the result of the optimization. In the lp example, an optimal solution is written to a solution file (model.sol).

There are many other things you can do once you have read and solved the model. For example, lp checks the solution status — which is highly recommended. If the model is found to be infeasible, this example computes an Irreducible Inconsistent Subsystem (IIS) to isolate the source of the infeasibility.

Try Gurobi for Free

Choose the evaluation license that fits you best, and start working with our Expert Team for technical guidance and support.

Evaluation License
Get a free, full-featured license of the Gurobi Optimizer to experience the performance, support, benchmarking and tuning services we provide as part of our product offering.
Academic License
Gurobi supports the teaching and use of optimization within academic institutions. We offer free, full-featured copies of Gurobi for use in class, and for research.
Cloud Trial

Request free trial hours, so you can see how quickly and easily a model can be solved on the cloud.