optimizer.py 5.58 KB
Newer Older
Bowen Wu's avatar
Bowen Wu committed
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
import xml.etree.ElementTree as ET
from cplex import Cplex
import gurobipy as gp
from mps_util import VerbosePrint

# Solver status
OPTIMAL = 0
INFEASIBLE = 1
INF_OR_UNBD = 2
UNBOUNDED = 3
UNKNOWN = 4

status_text = {
    OPTIMAL : "optimal",
    INFEASIBLE : "infeasible",
    INF_OR_UNBD : "infeasible or unbounded",
    UNBOUNDED : "unbounded",
    UNKNOWN : "unknown"
}

class Solver(object):
    def __init__(self, verbose = False) -> None:
        # by default, the solvers are very talky but we can make it less verbose
        self.verbose = verbose
        self.stats = dict()
        for k in [OPTIMAL, INFEASIBLE, INF_OR_UNBD, UNBOUNDED, UNKNOWN]:
            self.stats[k] = 0
    
    def print_solver_stats(self) -> None:
        print("\n", self.__class__.__name__, " Stats:")
        for k in self.stats:
            print(status_text[k], " = ", self.stats[k], " times")

class CplexSolver(Solver):
    # https://www.tu-chemnitz.de/mathematik/discrete/manuals/cplex/doc/refman/html/appendixB.html
    status_code = {
        # LP
        1 : OPTIMAL,
        2 : UNBOUNDED,
        3 : INFEASIBLE,
        4 : INF_OR_UNBD,
        # MIP
        101 : OPTIMAL, 
        102 : OPTIMAL,
Bowen Wu's avatar
Bowen Wu committed
45
46
47
48
        115 : OPTIMAL, # https://www-eio.upc.edu/lceio/manuals/cplex-11/html/usrcplex/solveLP19.html
        103 : INFEASIBLE,
        118 : UNBOUNDED,
        119 : INF_OR_UNBD
Bowen Wu's avatar
Bowen Wu committed
49
50
51
52
53
54
    }

    def __init__(self, verbose = False) -> None:
        super().__init__(verbose)

    def __call__(self, mps_file: str) -> dict:
Bowen Wu's avatar
Bowen Wu committed
55
56
57
58
59
60
        model = Cplex()
        model.set_results_stream(None)
        model.set_warning_stream(None)
        model.set_error_stream(None)
        model.set_log_stream(None)

Bowen Wu's avatar
Bowen Wu committed
61
        with VerbosePrint(self.verbose):
Bowen Wu's avatar
Bowen Wu committed
62
            model.read(mps_file)
Bowen Wu's avatar
Bowen Wu committed
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
            model.solve()     

        if self.get_sol_status(model.solution) == INF_OR_UNBD:
            model.parameters.preprocessing.presolve.set(0)
            with VerbosePrint(self.verbose):
                model.solve()

        ret = dict()
        ret["status"] = self.get_sol_status(model.solution)
        self.stats[ret["status"]] += 1

        if ret["status"] == OPTIMAL:
            ret["obj_val"] = self.get_obj_val(model.solution)
            ret["var_val"] = self.get_var_val(model.solution, model.variables)

        return ret

    def get_sol_status(self, sol) -> int:
        try:
            return CplexSolver.status_code[sol.get_status()]
        except KeyError:
            return UNKNOWN
    
    def get_obj_val(self, sol) -> float:
        return sol.get_objective_value()

    def get_var_val(self, sol, var) -> dict:
        ret = dict()
        for name in var.get_names():
            ret[name] = sol.get_values(name)
        return ret

    def get_sol_status_xml(self, sol: ET.ElementTree) -> int:
        root = sol.getroot()
        header = root.find('header')
        status = header.get('solutionStatusString')
        if status == 'optimal':
            return OPTIMAL
        elif status == 'infeasible':
            return INFEASIBLE
        else:
            return UNKNOWN

    def get_obj_val_xml(self, sol: ET.ElementTree) -> float:
        root = sol.getroot()
        header = root.find('header')
        return float(header.get('objectiveValue'))

    def get_var_val_xml(self, sol: ET.ElementTree) -> dict:
        root = sol.getroot()
        variables = root.find('variables')
        ret = dict()
        for var in variables.iter(tag = "variable"):
            name = var.get("name")
            val = float(var.get("value"))
            ret[name] = val
        return ret

class GurobiSolver(Solver):
    """ Gurobi Solver Wrapper
    Python interface documentation: 
    https://www.gurobi.com/documentation/9.5/refman/py_model.html#pythonclass:Model
    """
    # https://www.gurobi.com/documentation/9.5/refman/optimization_status_codes.html#sec:StatusCodes
    status_code = {
        2 : OPTIMAL,
        3 : INFEASIBLE,
        4 : INF_OR_UNBD,
        5 : UNBOUNDED
    }

    def __init__(self, verbose = False) -> None:
        super().__init__(verbose)

    def __call__(self, mps_file: str) -> dict:
        with VerbosePrint(self.verbose):
            model = gp.read(mps_file)
Bowen Wu's avatar
Bowen Wu committed
140
            model.setParam("OutputFlag", False)
Bowen Wu's avatar
Bowen Wu committed
141
142
143
144
145
146
147
148
            model.optimize()
        
        if self.get_sol_status(model) == INF_OR_UNBD:
            # https://www.gurobi.com/documentation/9.5/refman/dualreductions.html#parameter:DualReductions
            with VerbosePrint(self.verbose):
                model.setParam("DualReductions", 0)
                model.optimize()
        
149
150
151
152
153
154
155
        if self.get_sol_status(model) == UNBOUNDED:
            # set the obj val to 0 and re-optimize
            # in Gurobi, unbound does not imply feasible
            with VerbosePrint(self.verbose):
                model.setObjective(0, model.ModelSense)
                model.optimize()

Bowen Wu's avatar
Bowen Wu committed
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
        ret = dict()
        ret["status"] = self.get_sol_status(model)
        self.stats[ret["status"]] += 1

        if ret["status"] == OPTIMAL:
            ret["obj_val"] = self.get_obj_val(model)
            ret["var_val"] = self.get_var_val(model)

        return ret

    def get_sol_status(self, model) -> int:
        return GurobiSolver.status_code[model.Status]

    def get_obj_val(self, model) -> float:
        return model.ObjVal

    def get_var_val(self, model) -> dict:
        ret = dict()
        for v in model.getVars():
            ret[v.VarName] = v.X
        return ret

if __name__ == "__main__":
    mps_file = "mps/testprob_int.mps"
    cpx = CplexSolver()
    grb = GurobiSolver()
    print(cpx(mps_file))
    print(grb(mps_file))
    cpx.print_solver_stats()
Bowen Wu's avatar
Bowen Wu committed
185
    grb.print_solver_stats()