Search code examples
python-2.7cplex

How to get optimality gap using CPLEX Python API?


How can the optimality gap (relative and absolute) be obtained using CPLEX Python API (CPLEX 12.5, Python 2.7.15)? Is there any function such as get_optimal_gap() that would give the optimality gap? Or is parsing the output (as mentioned here) the only way? I see that there are custom functions such as solution.get_objective_value() - it would be nice if someone can suggest online resources that have a list of all functions that can be applied on the cplex object/file. Currently I am using the following code (courtesy: this IBM document):

    import cplex
    import sys

    def sample1(filename):
        c = cplex.Cplex(filename)
        try:
            c.solve()
        except CplexSolverError:
            print "Exception raised during solve"
            return

        # solution.get_status() returns an integer code
        status = c.solution.get_status()
        print "Solution status = " , status, ":",
        print c.solution.status[status]
        print "Objective value = " , c.solution.get_objective_value()

    sample1(filename)

Solution

  • The documentation for the CPLEX Python API is here (currently version 12.8).

    To get the relative mip gap, you can use c.solution.MIP.get_mip_relative_gap(). To calculate the absolute mip gap you'll need c.solution.MIP.get_best_objective().

    If you haven't already, you'll also want to take a look at the CPX_PARAM_EPGAP and CPX_PARAM_EPAGAP parameters.