Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Minimizing a function while keeping some of the variables constant

I have a function of the form

def tmp(x,n):
    R, s, a, T = x[0], x[1], x[2], x[3]

which returns a float, after a long block of calculations.

I need to minimize this function and for that I used the scipy.optimize.minimize():

minimize(tmp,[0,0,3,60000], args=(n,),tol =1e-15)

The above code looks for the minimum of the function tmp() with the starting values as shown.

Now I need to minimize the same function tmp, but keeping the variables R,T out of the minimization, as parameters. In other words I want the function to be written like:

def tmp(x,n,R,T):
        s, a = x[0], x[1]

How is it possible to create a function like the above without editing my first function?

like image 619
milia Avatar asked Feb 03 '26 23:02

milia


2 Answers

By default it isn't possible. You need to give tmp(x,n,R,T) a different name.

It's possible though, using the multimethod library

like image 139
Magnun Leno Avatar answered Feb 05 '26 13:02

Magnun Leno


The answer I have found to this problem is to use lmfit which allows you to easily hold some parameters fixed while minimizing on the others.

Here is a simple example where the function is minimized with respect to the second two parameters while the first one is held fixed :

import lmfit

p = lmfit.Parameters()
p.add_many(('param1',1.0,False,0,1)
           ,('param2',1.0,True,0,1)
           ,('param3',3.,True,10,30))


def function(p) :
    return (1-p['param1']) + (2-p['param2'])**2 + (1-p['param3'])**3

best_fit_result = lmfit.minimize(function,p,method='Nelder')

print(best_fit_result.params)
like image 37
RBM Avatar answered Feb 05 '26 12:02

RBM



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!