#! /usr/bin/env python3 # def cvxopt_example ( ): # from cvxopt import matrix from cvxopt import solvers print ( '' ) print ( 'cvxopt_example:' ) print ( ' cvxopt is a quadratic programming package.' ) print ( '' ) print ( ' Use it to solve the following system:' ) print ( '' ) print ( ' minimize:' ) print ( ' 2 x0^2 + x1^2 + x0 x1 + x0 + x1' ) print ( ' subject to:' ) print ( ' x0 >= 0' ) print ( ' x1 >= 0' ) print ( ' x0 + x1 = 1' ) print ( '' ) print ( ' Reformulated for cvxopt as follows:' ) print ( '' ) print ( ' minimize:' ) print ( ' 1/2 x\' Q x + p' ) print ( ' subject to: ') print ( ' G x <= h' ) print ( ' A x = b' ) Q = 2*matrix([ [2, .5], [.5, 1] ]) p = matrix([1.0, 1.0]) G = matrix([[-1.0,0.0],[0.0,-1.0]]) h = matrix([0.0,0.0]) # # A must be a matrix. # We have to add the (1,2) argument at the end here to indicate # that A should be set up as a two-dimensional object, not a vector. # A = matrix([1.0, 1.0], (1,2)) b = matrix(1.0) # # The output "sol" is a dictionary. # The information we want is stored under 'x'. # sol = solvers.qp ( Q, p, G, h, A, b ) import numpy as np x = np.array ( sol['x'] ) x = np.squeeze ( x ) print ( '' ) print ( ' Cost is minimized at x = [', x[0],',', x[1], ']' ) cost = 2.0 * x[0]**2 + x[1]**2 + x[0]*x[1] + x[0] + x[1] print ( ' Minimized cost is ', cost ) return if ( __name__ == '__main__' ): cvxopt_example ( )