2

I am using scipy library for an optimization task. I have a function which has to be minimized. My code and function looks like

import numpy as np
from scipy.optimize import minimize
from scipy.optimize import Bounds


bounds = Bounds([2,10],[5,20])

x0 = np.array([2.5,15])

def objective(x):
    x0 = x[0]
    x1 = x[1]
    return a*x0 + b*x0*x1 - c*x1*x1

res = minimize(objective, x0, method='trust-constr',options={'verbose': 1}, bounds=bounds)

My a,b and c values change over time and are not constant. The function should not be optimized for a,b,c values but should be optimized for a given a,b,c values which can change over time. How do I give these values as an input to the objective function?

chink
  • 1,505
  • 3
  • 28
  • 70

1 Answers1

3

The documentation for scipy.optimize.minimize mentions the args parameter:

args : tuple, optional

Extra arguments passed to the objective function and its derivatives (fun, jac and hess functions).

You can use it as follows:

import numpy as np
from scipy.optimize import minimize
from scipy.optimize import Bounds

bounds = Bounds([2,10],[5,20])
x0 = np.array([2.5,15])

def objective(x, *args):
    a, b, c = args  # or just use args[0], args[1], args[2]
    x0 = x[0]
    x1 = x[1]
    return a*x0 + b*x0*x1 - c*x1*x1

# Pass in a tuple with the wanted arguments a, b, c
res = minimize(objective, x0, args=(1,-2,3), method='trust-constr',options={'verbose': 1}, bounds=bounds)
Community
  • 1
  • 1
rtoijala
  • 1,200
  • 10
  • 20