-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathQP.py
More file actions
30 lines (23 loc) · 1.4 KB
/
QP.py
File metadata and controls
30 lines (23 loc) · 1.4 KB
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
import numpy as np
from cvxopt import matrix, solvers
class QP(object):
def __init__(self):
super().__init__()
self.LagrangeMultipliers = None
def QP(self, Q: np.array, c: np.array, A: np.array, b: np.array) -> np.array:
"""Minimize_x 1/2*x^T*Q*x+c^T*x subject to A*x<=b for given matrices Q (symmetric) and A and given vectors c and b. """
# long live global options, which cannot be set locally
# sol = solvers.qp(matrix(np.asfarray(Q)), matrix(np.asfarray(c)),
# matrix(np.asfarray(A)), matrix(np.asfarray(b)), options={'show_progress': False})
# sol with np.asarray with dtype float, because np.asfarray deprecated since numpy 2.0
sol = solvers.qp(matrix(np.asarray(Q, dtype=float)), matrix(np.asarray(c, dtype=float)),
matrix(np.asarray(A, dtype=float)), matrix(np.asarray(b, dtype=float)), options={'show_progress': False})
self.LagrangeMultipliers = np.array(sol['z'])
return np.array(sol['x']).flatten()
# qp = QP()
# print(qp.QP(np.array([[2.0]]), np.array([[-2]]),
# np.array([[1.0]]), np.array([0.5])))
# print(qp.QP(np.array([[2.0]]), np.array([[-2]]),
# np.array([[1.0]]), np.array([1.0])))
# print(qp.QP(np.array([[2.0]]), np.array([[-2]]),
# np.array([[1.0]]), np.array([1.5])))