user2702405
user2702405

Reputation: 111

scipy.optimize with non linear constraints

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)

Upvotes: 4

Views: 10796

Answers (1)

Cleb
Cleb

Reputation: 26037

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.

Upvotes: 4

Related Questions