cvxopt for linear and quadratic program

# -*- coding: utf-8 -*-
“””
Created on Sun Nov 5 08:03:26 2017
http://cvxopt.org/examples/tutorial/qp.html
“””

#1. Solving a linear program
”’ Linear programs can be specified via the solvers.lp() function.
As an example, we can solve the problem

minimize 2*x1+x2
subject to
-x1+x2<=1
x1+x2>=2
x2>=0
x1-2*x2<=4

the st is equal to
-x1+x2<=1
-x1-x2<=-2
-x2<=0
x1-2*x2<=4

”’

import cvxopt as op
A = op.matrix([ [-1.0, -1.0, 0.0, 1.0],
[1.0, -1.0, -1.0, -2.0] ])
b = op.matrix( [ 1.0, -2.0, 0.0, 4.0 ])
c = op.matrix( [ 2.0, 1.0 ])
sol=op.solvers.lp(c,A,b)
print(sol[‘x’])

#%%2. Solving a quadratic program

”’
minimize 2*x1**2+x2**2+x1*x2+x1+x2
st
x1>=0
x2>=0
x1+x2=1

the object and st are equal to

[x1, x2] *[[2,.5],[.5,1]] *[[x1],[x2]]

st
-x1 <=0
-x2<=0
x1+x2 =1

op.solvers.qp(P, q, G=None, h=None, A=None, b=None, solver=None,
kktsolver=None, initvals=None, **kwargs)

Solves a quadratic program
minimize (1/2)*x’*P*x + q’*x
subject to G*x <= h
A*x = b.
Input arguments.
P is a n x n dense or sparse ‘d’ matrix with the lower triangular part of P stored in the lower triangle. Must be positive semidefinite.
q is an n x 1 dense ‘d’ matrix.
G is an m x n dense or sparse ‘d’ matrix.
h is an m x 1 dense ‘d’ matrix.
A is a p x n dense or sparse ‘d’ matrix.
b is a p x 1 dense ‘d’ matrix or None.
solver is None or ‘mosek’.
The default values for G, h, A and b are empty matrices with zero rows.
”’

P = 2*op.matrix([ [2, .5],
[.5, 1] ])
q = op.matrix( [1.0, 1.0])

G = op.matrix([[-1.0,0.0],
[0.0,-1.0]])
h = op.matrix( [0.0,0.0])

A = op.matrix( [1.0, 1.0], (1,2)) # with 1 row, 2 columns
b = op.matrix(1.0)
sol=op.solvers.qp(P, q, G, h, A, b)

print(sol[‘x’])

分享到: 微信 新浪微博 更多
Print Friendly, PDF & Email

发表评论

您的电子邮箱地址不会被公开。 必填项已用*标注