Search code examples
pythonpython-2.7cvxopt

Displaying optimal solution in cvxopt


Is there a way to only display the optimal values in cvxopt without displaying the iterative values such as pcost,dcost ,gap etc as shown in below example,

n = 5 #no. of design variables
P = spmatrix(1,range(n),range(n))
q = matrix([[60.341,13.05,1.217,5.5,24.2]])
m = matrix([[0,0,-2.778,-0.002657,0,0.3004,0],[0.6168,0,0,-0.0005693,0,0.06217,0],[0,5,0,0,0,0,0],[-0.8987,0,0,0,-0.000462,0,0.1554],[0,0,3.33,0,-0.001943,0,0.683]])
nl = spmatrix(-1,range(n),range(n))
nu = spmatrix(1,range(n),range(n))
G = matrix([m,nl,nu])
h = matrix([0.0113,1,0.167,0.20289,0.5129,0.9098,0.829,0.05,0.45,0,0.35,0,0.1,1.55,10,1.4,0.15])
qp = solvers.qp(P,q,G,h)
print qp['x']

Output:

    pcost       dcost       gap    pres   dres
0: -1.0569e+03 -4.5953e+02  3e+03  6e+00  2e+00
1: -1.1312e+02 -1.5294e+02  6e+02  8e-01  2e-01
2: -1.8148e-01 -5.6851e+01  6e+01  2e-16  7e-15
3: -6.5682e+00 -1.6549e+01  1e+01  9e-17  7e-16
4: -1.0162e+01 -1.1053e+01  9e-01  3e-16  2e-16
5: -1.0470e+01 -1.0624e+01  2e-01  6e-17  3e-16
6: -1.0502e+01 -1.0506e+01  4e-03  1e-16  4e-16
7: -1.0503e+01 -1.0503e+01  4e-05  7e-17  2e-16
8: -1.0503e+01 -1.0503e+01  4e-07  1e-16  2e-16
Optimal solution found.
[-5.00e-02]
[-4.50e-01]
[ 1.97e-08]
[-3.21e-01]
[ 7.81e-10]

I want to print only the last 5 values of output.


Solution

  • Just turn off verbose-mode (in cvxopt called show_progress) as explained in the docs.

    from cvxopt import spmatrix, matrix, solvers
    solvers.options['show_progress'] = False        # !!!
    
    n = 5 #no. of design variables
    P = spmatrix(1,range(n),range(n))
    q = matrix([[60.341,13.05,1.217,5.5,24.2]])
    m = matrix([[0,0,-2.778,-0.002657,0,0.3004,0],
    [0.6168,0,0,-0.0005693,0,0.06217,0],[0,5,0,0,0,0,0],
    [-0.8987,0,0,0,-0.000462,0,0.1554],[0,0,3.33,0,-0.001943,0,0.683]])
    nl = spmatrix(-1,range(n),range(n))
    nu = spmatrix(1,range(n),range(n))
    G = matrix([m,nl,nu])
    h = matrix([0.0113,1,0.167,0.20289,0.5129,0.9098,0.829,0.05,0.45,0,0.35,0,0.1,1.55,10,1.4,0.15])
    qp = solvers.qp(P,q,G,h)
    print(qp['x'])
    

    Output:

    [-5.00e-02]
    [-4.50e-01]
    [ 1.97e-08]
    [-3.21e-01]
    [ 7.81e-10]