scipy.optimize with non linear constraints

∥☆過路亽.° 提交于 2020-01-24 13:58:48

问题


I have non-linear function with non-linear constraints and I'd like to optimize it. I don't know how to define non-linear constraints using scipy.optimize. My code so far looks like:

from math import cos, atan
import numpy as np
from scipy.optimize import minimize
import sympy as sy

def f(x):
    return 0.1*x*y

def ineq_constraint(x):
    x**2 + y**2 - (5+2.2*sy.cos(10*sy.atan(x/y)))**2
    return x,y

con = {'type': 'ineq', 'fun': ineq_constraint}
minimize(f,x0,method='SLSQP',constraints=con)

回答1:


The were a few minor issues with the code; here is the modified version (explanation below):

from math import cos, atan
import numpy as np
from scipy.optimize import minimize


def f(x):
    return 0.1 * x[0] * x[1]

def ineq_constraint(x):
    return x[0]**2 + x[1]**2 - (5. + 2.2 * cos(10 * atan(x[0] / x[1])))**2


con = {'type': 'ineq', 'fun': ineq_constraint}
x0 = [1, 1]
res = minimize(f, x0, method='SLSQP', constraints=con)

The res looks as follows:

     fun: 0.37229877398896682
     jac: array([ 0.16372866,  0.22738743,  0.        ])
 message: 'Optimization terminated successfully.'
    nfev: 96
     nit: 22
    njev: 22
  status: 0
 success: True
       x: array([ 2.27385837,  1.63729975])

One problem was that x and y were not defined in your functions, I replaced them by x[0] and x[1], respectively; also there was no need to use sympy to define your constraints and you want to return the actual constraint and not x and y.



来源:https://stackoverflow.com/questions/43309877/scipy-optimize-with-non-linear-constraints

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!