pythonpython-2.7optimizationnlopt

NLopt minimize eigenvalue, Python


I have matrices where elements can be defined as arithmetic expressions and have written Python code to optimise parameters in these expressions in order to minimize particular eigenvalues of the matrix. I have used scipy to do this, but was wondering if it is possible with NLopt as I would like to try a few more algorithms which it has (derivative free variants).

In scipy I would do something like this:

import numpy as np
from scipy.linalg import eig
from scipy.optimize import minimize

def my_func(x):
    y, w = x
    arr = np.array([[y+w,-2],[-2,w-2*(w+y)]])
    ev, ew=eig(arr)
    return ev[0]

x0 = np.array([10, 3.45])  # Initial guess

minimize(my_func, x0)

In NLopt I have tried this:

import numpy as np
from scipy.linalg import eig
import nlopt

def my_func(x,grad):
    arr = np.array([[x[0]+x[1],-2],[-2,x[1]-2*(x[1]+x[0])]])
    ev, ew=eig(arr)
    return ev[0]

opt = nlopt.opt(nlopt.LN_BOBYQA, 2)
opt.set_lower_bounds([1.0,1.0])
opt.set_min_objective(my_func)
opt.set_xtol_rel(1e-7)
x = opt.optimize([10.0, 3.5])
minf = opt.last_optimum_value()
print "optimum at ", x[0],x[1]
print "minimum value = ", minf
print "result code = ", opt.last_optimize_result()

This returns:

ValueError: nlopt invalid argument

Is NLopt able to process this problem?


Solution

  • my_func should return double, posted sample return complex

    print(type(ev[0]))
    None
    <class 'numpy.complex128'>
    
    ev[0]
    (13.607794065928395+0j)
    

    correct version of my_func:

    def my_func(x, grad):
        arr = np.array([[x[0]+x[1],-2],[-2,x[1]-2*(x[1]+x[0])]])
        ev, ew=eig(arr)
        return ev[0].real
    

    updated sample returns:

    optimum at  [ 1.  1.]
    minimum value =  2.7015621187164243
    result code =  4