forked from porld/posflux
-
Notifications
You must be signed in to change notification settings - Fork 0
/
lp_solver.py
89 lines (70 loc) · 2.55 KB
/
lp_solver.py
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
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
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
'''
(c) University of Liverpool 2019
All rights reserved.
'''
# pylint: disable=invalid-name
# pylint: disable=too-many-arguments
# pylint: disable=too-many-locals
from gurobipy import Model, GRB, LinExpr
def run_gurobi_lp(lp):
'''Run Gurobi.'''
lp.optimize()
return lp
def create_gurobi_lp(lhs, equalities, rhs, variable_types, lbs, ubs, objs):
'''
lhs is a CSR matrix of size c * v (constraints * variables)
with nonzero coefficients
equalities is a list of size c containing equalities, inequalities
RHS is a list of size c of values (for now no functions are included)
variable_types is a list of variables types
lbs,ubs are lists of size v containing lower and upper bounds
objective is the dictionary of non-zero elements and their weights
(virtually of size v, though in practice often smaller)
'''
# Create model
lp = Model("LP")
# Create variables, note all variables here are continuous
print('\tCreate Gurobi variables')
for var_index, variable_type in enumerate(variable_types):
# Identify variable type
if variable_type == 'continuous':
var_type = GRB.CONTINUOUS
elif variable_type == 'binary':
var_type = GRB.BINARY
else:
var_type = 'unknown'
# Identify whether objective
if var_index in objs:
objective_value = objs.get(var_index)
else:
objective_value = 0.0
# Create variable
lp.addVar(lbs[var_index], ubs[var_index], objective_value,
var_type, 'v' + str(var_index))
# Integrate new variables
lp.update()
lpvars = lp.getVars() # List of variable objects
# Create constraints
print('\tCreate Gurobi constraints')
for cons_index, _ in enumerate(equalities):
lin = [] # Coefficients
refs = [] # Variables
row = lhs.getrow(cons_index)
_, variables = row.nonzero()
lin = row.data
for r in variables:
# coeff = row.getcol(r).toarray()[0][0]
refs.append(lpvars[r])
if equalities[cons_index] == '>':
equality = GRB.GREATER_EQUAL
elif equalities[cons_index] == '<':
equality = GRB.LESS_EQUAL
elif equalities[cons_index] == '=':
equality = GRB.EQUAL
else:
equality = ''
lp.addConstr(LinExpr(lin, refs), equality,
rhs[cons_index], 'c' + str(cons_index))
# Integrate new constraints
lp.update()
return lp