0

If I have a function func(x1,x2,x3), can I use the minimize function scipy.optimize.minimize with excluding x3 from the optimization process, where x3 is defined as numpy array. How can I define the argument in this case?. I'm supposed to get an array containing the minimum values of func for each value of x3.

For example:

def func(thet1,phai1,thet2,phai2,c2):
    
    RhoABC = np.array([[1,0,thet1,0,0,0,0,c1],[0,1,0,0,phai2,0,c2,0],[0,0,1,0,0,c2,thet2,0],[0,0,0,1,c2,0,0,0],[0,phai1,0,c2,1,0,0,0],[0,0,c2,0,0,1,0,thet2],[0,c2,0,0,0,0,1,0],[c1,0,0,phai1,0,0,0,1]])   
    w, v = np.linalg.eig(RhoABC)  
    return w[1] 

I want to minimize it where c2 = linspace(-1,1,10) and the angles belong to (0,2pi)

Bekaso
  • 135
  • 5
  • 1
    I don't fully understand your question, but you could use *args and then put the argument x3, this way, you don't have to assign it a value every time you call it. – jimmie_roggers Jul 25 '21 at 07:19
  • @jimmie_roggers Thank you for your reply. I think this is a solution to my problem but I don't know how to implement it. I made my question clear, please take a look. – Bekaso Jul 25 '21 at 07:41

2 Answers2

1

Maybe you could use something like this:

def func(thet1,phai1,thet2,phai2,*args, c2 = []):
#considering c2 to be x3 in the above post
    
    RhoABC = np.array([[1,0,thet1,0,0,0,0,c1],[0,1,0,0,phai2,0,c2,0],[0,0,1,0,0,c2,thet2,0],[0,0,0,1,c2,0,0,0],[0,phai1,0,c2,1,0,0,0],[0,0,c2,0,0,1,0,thet2],[0,c2,0,0,0,0,1,0],[c1,0,0,phai1,0,0,0,1]])   
    w, v = np.linalg.eig(RhoABC)  
    return w[1] 

Then when you call the function:

retVal = func(thet1,phai1,thet2,phai2, c2=c2)

#you have to specify c2 first and then equate it to the value since this is an optional argument.
0

As an alternative to jimmie's answer, you can use a lambda function and the unpacking operator *:

minimize(lambda x: func(*x, linspace(-1,1,10)), x0=x0, ...)

will minimize the function func for the variables thet1,phai1,thet2,phai2 with given c2=linspace(-1,1,10).

joni
  • 6,840
  • 2
  • 13
  • 20
  • In this case, would `def func(thet1,phai1,thet2,phai2,*args, c2 = []):` remain as it is? – Bekaso Jul 26 '21 at 05:23
  • @Bekaso No, it's your initial function signature, i.e. `def func(thet1,phai1,thet2,phai2,c2)`. – joni Jul 26 '21 at 06:01