/
qp_solver.py
443 lines (359 loc) · 13 KB
/
qp_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
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
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
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
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
"""Solvers for the linear and quadratic programs in active subspaces."""
import numpy as np
from scipy.optimize import linprog, minimize
# checking to see if system has gurobi
try:
HAS_GUROBI = True
import gurobipy as gpy
except ImportError, e:
HAS_GUROBI = False
pass
# string constants for QP solver names
solver_SCIPY = 'SCIPY'
solver_GUROBI = 'GUROBI'
class QPSolver():
"""A class for solving linear and quadratic programs.
Attributes
----------
solver : str
identifies which linear program software to use
Notes
-----
The class checks to see if Gurobi is present. If it is, it uses Gurobi to
solve the linear and quadratic programs. Otherwise, it uses scipy
implementations to solve the linear and quadratic programs.
"""
solver = None
def __init__(self, solver='GUROBI'):
"""Initialize a QPSolver.
Parameters
----------
solver : str, optional
identifies which linear program software to use. Options are
'GUROBI' and 'SCIPY'. (default 'GUROBI')
"""
if solver==solver_GUROBI and HAS_GUROBI:
self.solver = solver_GUROBI
elif solver=='SCIPY':
self.solver = solver_SCIPY
else:
self.solver = solver_SCIPY
def linear_program_eq(self, c, A, b, lb, ub):
"""Solves an equality constrained linear program with variable bounds.
This method returns the minimizer of the following linear program.
minimize c^T x
subject to A x = b
lb <= x <= ub
Parameters
----------
c : ndarray
m-by-1 matrix for the linear objective function
A : ndarray
M-by-m matrix that contains the coefficients of the linear equality
constraints
b : ndarray
M-by-1 matrix that is the right hand side of the equality
constraints
lb : ndarray
m-by-1 matrix that contains the lower bounds on the variables
ub : ndarray
m-by-1 matrix that contains the upper bounds on the variables
Returns
-------
x : ndarray
m-by-1 matrix that is the minimizer of the linear program
"""
if self.solver == solver_SCIPY:
return _scipy_linear_program_eq(c, A, b, lb, ub)
elif self.solver == solver_GUROBI:
return _gurobi_linear_program_eq(c, A, b, lb, ub)
else:
raise ValueError('QP solver {} not available'.format(self.solver))
def linear_program_ineq(self, c, A, b):
"""Solves an inequality constrained linear program.
This method returns the minimizer of the following linear program.
minimize c^T x
subject to A x >= b
Parameters
----------
c : ndarray
m-by-1 matrix for the linear objective function
A : ndarray
M-by-m matrix that contains the coefficients of the linear equality
constraints
b : ndarray
size M-by-1 matrix that is the right hand side of the equality
constraints
Returns
-------
x : ndarray
m-by-1 matrix that is the minimizer of the linear program
"""
if self.solver == solver_SCIPY:
return _scipy_linear_program_ineq(c, A, b)
elif self.solver == solver_GUROBI:
return _gurobi_linear_program_ineq(c, A, b)
else:
raise ValueError('QP solver {} not available'.format(self.solver))
def quadratic_program_bnd(self, c, Q, lb, ub):
"""Solves a quadratic program with variable bounds.
This method returns the minimizer of the following linear program.
minimize c^T x + x^T Q x
subject to lb <= x <= ub
Parameters
----------
c : ndarray
m-by-1 matrix that contains the coefficients of the linear term in
the objective function
Q : ndarray
m-by-m matrix that contains the coefficients of the quadratic term
in the objective function
lb : ndarray
m-by-1 matrix that contains the lower bounds on the variables
ub : ndarray
m-by-1 matrix that contains the upper bounds on the variables
Returns
-------
x : ndarray
m-by-1 matrix that is the minimizer of the quadratic program
"""
if self.solver == solver_SCIPY:
return _scipy_quadratic_program_bnd(c, Q, lb, ub)
elif self.solver == solver_GUROBI:
return _gurobi_quadratic_program_bnd(c, Q, lb, ub)
else:
raise ValueError('QP solver {} not available'.format(self.solver))
def quadratic_program_ineq(self, c, Q, A, b):
"""Solves an inequality constrained quadratic program.
This method returns the minimizer of the following quadratic program.
minimize c^T x + x^T Q x
subject to A x >= b
Parameters
----------
c : ndarray
m-by-1 matrix that contains the coefficients of the linear term in
the objective function
Q : ndarray
m-by-m matrix that contains the coefficients of the quadratic term
in the objective function
A : ndarray
M-by-m matrix that contains the coefficients of the linear equality
constraints
b : ndarray
M-by-1 matrix that is the right hand side of the equality
constraints
Returns
-------
x : ndarray
m-by-1 matrix that is the minimizer of the quadratic program.
"""
if self.solver == solver_SCIPY:
return _scipy_quadratic_program_ineq(c, Q, A, b)
elif self.solver == solver_GUROBI:
return _gurobi_quadratic_program_ineq(c, Q, A, b)
else:
raise ValueError('QP solver {} not available'.format(self.solver))
def _scipy_linear_program_eq(c, A, b, lb, ub):
c = c.reshape((c.size,))
b = b.reshape((b.size,))
# make bounds
bounds = []
for i in range(lb.size):
bounds.append((lb[i,0], ub[i,0]))
res = linprog(c, A_eq=A, b_eq=b, bounds=bounds, options={"disp": False})
if res.success:
return res.x.reshape((c.size,1))
else:
np.savez('bad_scipy_lp_eq_{:010d}'.format(np.random.randint(int(1e9))),
c=c, A=A, b=b, lb=lb, ub=ub, res=res)
raise Exception('Scipy did not solve the LP. Blame Scipy.')
return None
def _scipy_linear_program_ineq(c, A, b):
c = c.reshape((c.size,))
b = b.reshape((b.size,))
# make unbounded bounds
bounds = []
for i in range(c.size):
bounds.append((None, None))
A_ub, b_ub = -A, -b
res = linprog(c, A_ub=A_ub, b_ub=b_ub, bounds=bounds, options={"disp": False})
if res.success:
return res.x.reshape((c.size,1))
else:
np.savez('bad_scipy_lp_ineq_{:010d}'.format(np.random.randint(int(1e9))),
c=c, A=A, b=b, res=res)
raise Exception('Scipy did not solve the LP. Blame Scipy.')
return None
def _scipy_quadratic_program_bnd(c, Q, lb, ub):
# define the objective and gradient
def fun(x):
f = np.dot(x, c) + np.dot(x, np.dot(Q, x.T))
return f[0]
def jac(x):
j = c.T + 2.0*np.dot(x, Q)
return j[0]
# make bounds
bounds = []
for i in range(lb.size):
bounds.append((lb[i,0],ub[i,0]))
x0 = np.zeros((c.size,))
res = minimize(fun, x0, method='L-BFGS-B', jac=jac,
bounds=bounds, options={"disp": False})
if res.success:
xstar = res.x
if isinstance(xstar, float):
xstar = np.array([[xstar]])
return xstar.reshape((c.size,1))
else:
np.savez('bad_scipy_qp_bnd_{:010d}'.format(np.random.randint(int(1e9))),
c=c, Q=Q, lb=lb, ub=ub, res=res)
raise Exception('Scipy did not solve the LP. Blame Scipy.')
return None
def _scipy_quadratic_program_ineq(c, Q, A, b):
b = b.reshape((b.size,))
# define the objective and gradient
def fun(x):
f = np.dot(x, c) + np.dot(x, np.dot(Q, x.T))
return f[0]
def jac(x):
j = c.T + 2.0*np.dot(x, Q)
return j[0]
# inequality constraints
cons = ({'type':'ineq',
'fun' : lambda x: np.dot(A, x) - b,
'jac' : lambda x: A})
x0 = np.zeros((c.size,))
res = minimize(fun, x0, method='SLSQP', jac=jac,
constraints=cons, options={"disp": False})
if res.success:
xstar = res.x
if isinstance(xstar, float):
xstar = np.array([[xstar]])
return xstar.reshape((c.size,1))
else:
np.savez('bad_scipy_qp_ineq_{:010d}'.format(np.random.randint(int(1e9))),
c=c, Q=Q, A=A, b=b, res=res)
raise Exception('Scipy did not solve the LP. Blame Scipy.')
return None
def _gurobi_linear_program_eq(c, A, b, lb, ub):
m,n = A.shape
model = gpy.Model()
model.setParam('OutputFlag', 0)
# Add variables to model
vars = []
for j in range(n):
vars.append(model.addVar(lb=lb[j,0], ub=ub[j,0], vtype=gpy.GRB.CONTINUOUS))
model.update()
# Populate linear constraints
for i in range(m):
expr = gpy.LinExpr()
for j in range(n):
expr += A[i,j]*vars[j]
model.addConstr(expr, gpy.GRB.EQUAL, b[i,0])
# Populate objective
obj = gpy.LinExpr()
for j in range(n):
obj += c[j,0]*vars[j]
model.setObjective(obj)
model.update()
# Solve
model.optimize()
if model.status == gpy.GRB.OPTIMAL:
return np.array(model.getAttr('x', vars)).reshape((n,1))
else:
np.savez('bad_gurobi_lp_eq_{:010d}'.format(np.random.randint(int(1e9))),
c=c, A=A, b=b, lb=lb, ub=ub, model=model)
raise Exception('Gurobi did not solve the LP. Blame Gurobi.')
return None
def _gurobi_linear_program_ineq(c, A, b):
m,n = A.shape
model = gpy.Model()
model.setParam('OutputFlag', 0)
# Add variables to model
vars = []
for j in range(n):
vars.append(model.addVar(lb=-gpy.GRB.INFINITY,
ub=gpy.GRB.INFINITY, vtype=gpy.GRB.CONTINUOUS))
model.update()
# Populate linear constraints
for i in range(m):
expr = gpy.LinExpr()
for j in range(n):
expr += A[i,j]*vars[j]
model.addConstr(expr, gpy.GRB.GREATER_EQUAL, b[i,0])
# Populate objective
obj = gpy.LinExpr()
for j in range(n):
obj += c[j,0]*vars[j]
model.setObjective(obj)
model.update()
# Solve
model.optimize()
if model.status == gpy.GRB.OPTIMAL:
return np.array(model.getAttr('x', vars)).reshape((n,1))
else:
np.savez('bad_gurobi_lp_ineq_{:010d}'.format(np.random.randint(int(1e9))),
c=c, A=A, b=b, model=model)
raise Exception('Gurobi did not solve the LP. Blame Gurobi.')
return None
def _gurobi_quadratic_program_bnd(c, Q, lb, ub):
n = Q.shape[0]
model = gpy.Model()
model.setParam('OutputFlag', 0)
# Add variables to model
vars = []
for j in range(n):
vars.append(model.addVar(lb=lb[j,0], ub=ub[j,0], vtype=gpy.GRB.CONTINUOUS))
model.update()
# Populate objective
obj = gpy.QuadExpr()
for i in range(n):
for j in range(n):
obj += Q[i,j]*vars[i]*vars[j]
for j in range(n):
obj += c[j,0]*vars[j]
model.setObjective(obj)
model.update()
# Solve
model.optimize()
if model.status == gpy.GRB.OPTIMAL:
return np.array(model.getAttr('x', vars)).reshape((n,1))
else:
np.savez('bad_gurobi_qp_bnd_{:010d}'.format(np.random.randint(int(1e9))),
c=c, Q=Q, lb=lb, ub=ub, model=model)
raise Exception('Gurobi did not solve the QP. Blame Gurobi.')
return None
def _gurobi_quadratic_program_ineq(c, Q, A, b):
m,n = A.shape
model = gpy.Model()
model.setParam('OutputFlag', 0)
# Add variables to model
vars = []
for j in range(n):
vars.append(model.addVar(lb=-gpy.GRB.INFINITY,
ub=gpy.GRB.INFINITY, vtype=gpy.GRB.CONTINUOUS))
model.update()
# Populate linear constraints
for i in range(m):
expr = gpy.LinExpr()
for j in range(n):
expr += A[i,j]*vars[j]
model.addConstr(expr, gpy.GRB.GREATER_EQUAL, b[i,0])
# Populate objective
obj = gpy.QuadExpr()
for i in range(n):
for j in range(n):
obj += Q[i,j]*vars[i]*vars[j]
for j in range(n):
obj += c[j,0]*vars[j]
model.setObjective(obj)
model.update()
# Solve
model.optimize()
if model.status == gpy.GRB.OPTIMAL:
return np.array(model.getAttr('x', vars)).reshape((n,1))
else:
np.savez('bad_gurobi_qp_ineq_{:010d}'.format(np.random.randint(int(1e9))),
c=c, Q=Q, A=A, b=b, model=model)
raise Exception('Gurobi did not solve the QP. Blame Gurobi.')
return None