Search code examples
pythonlinear-programmingcplexpulp

How can I get the Relative/Absolute GAP from LP solution in Python with CPLEX Solver?


I'm solving a problem with PuLP in python and i'm trying to print the gap with solution.MIP.get_mip_relative_gap() but it doesn't work. Is there a way to get this information?


Solution

  • I would use orloge

    Let me share a small example out of the zoo example.

    import pulp
    import cplex
    import orloge
    
    
    
    
    bus_problem = pulp.LpProblem("bus", pulp.LpMinimize)
    
    nbBus40 = pulp.LpVariable('nbBus40', lowBound=0, cat='Integer')
    nbBus30 = pulp.LpVariable('nbBus30', lowBound=0, cat='Integer')
    
    # Objective function
    bus_problem += 500 * nbBus40 + 400 * nbBus30, "cost"
    
    # Constraints
    bus_problem += 40 * nbBus40 + 30 * nbBus30 >= 300
    
    
    solver = pulp.CPLEX_CMD(options=['set logfile c://temp//log.log','set mip limits solutions 2'])
    
    
    
    
    bus_problem.solve(solver)
    print(pulp.LpStatus[bus_problem.status])
    
    for variable in bus_problem.variables():
        print ("{} = {}".format(variable.name, variable.varValue))
    
    
    logs_dict = orloge.get_info_solver('c://temp//log.log',"CPLEX") 
    best_bound, best_solution = logs_dict["best_bound"], logs_dict["best_solution"]
    
    print("best_bound = ",best_bound)
    print("best_solution = ",best_solution)
    
    print("gap = ",abs(best_bound-best_solution)/(1e-10+abs(best_solution)))
    
                                 
    

    which gives

    Optimal
    nbBus30 = 1.0
    nbBus40 = 7.0
    best_bound =  3750.0
    best_solution =  3900.0
    gap =  0.03846153846153748