Quadratic optimization with cvxopt in Python

I have demonstrated how to solve linear problems using SciPy in Python, and how to solve non-linear optimization problems in R (e.g. with nloptr for gradient-descent optimization). In this post I want to show how to solve quadratic optimization tasks in Python, using the cvxopt-module.

Using the cvxopt-module in Python I will model and solve the problem below:

In order to solve this problem using the cvxopt-module in Python, one must restate the problem in vector-matrix notation form – such that it satifies the template below:

In below coding example I solve the problem above, stating it according to the given template in vector-matrix notation form:

# preparing the modelling inputs, using cvxopt
from cvxopt import matrix

# setting matrices and vectors
P = matrix([[2.0,0.0],[0.0,4.0]])
q = matrix([6.0,20.0])
G = matrix([[-1.0,-1.0],[-2.0,-3.0]])
h = matrix([-10.0,0.0])

# importing the solver from cvxopt-module, providing the solver function 
from cvxopt import solvers

# using the qp-solver from cvxopt.solvers
solution = solvers.qp(P=P,
                     q=q,
                     G=G,
                     h=h)
     pcost       dcost       gap    pres   dres
 0:  3.1195e+00  1.0142e+02  2e+01  1e+00  3e-01
 1:  1.1086e+02  1.1722e+02  4e+00  9e-02  2e-02
 2:  1.1727e+02  1.1733e+02  4e-02  9e-04  2e-04
 3:  1.1733e+02  1.1733e+02  4e-04  9e-06  2e-06
 4:  1.1733e+02  1.1733e+02  4e-06  9e-08  2e-08
Optimal solution found.
# optimal x1
solution["x"][0]
4.6666665332235375
# optimal x2
solution["x"][1]
2.6666665168063117
# optimal objective function value
solution["primal objective"] + 5
122.33332669148787

If interested, please go ahead and read my blog post on quadratic programming in R, using the quadprog R-package from CRAN.

Leave a Reply

Leave a Reply

Your email address will not be published. Required fields are marked *

Close

Meta