1

I am trying to optimize a cost function EL_c

EL_c=-300.49858410695*C_0 - 301*C_1 - 60.2000000000003*C_2

After confirming the free variables by using

EL_c.free_symbols={C_0,C_1,C_2}

I have tried to use

ff=lambdify(("C_0","C_1","C_2"),EL_c)

and then

x0=(1,1,1)
scipy.optimize.minimize(ff,x0,method="Nelder-Mead")

However, I get the error

TypeError: <lambda>() missing 2 required positional arguments: 'C_1' 
and 'C_2'

Ideally, I would like to be able to optimize the function using the above method.

TriposG
  • 103
  • 1
  • 2
  • 11
  • I guess you just need to change the call to minimize: don't put the variables for the lambda in a tuple, just drop them in minimize: `scipy.optimize.minimize(ff, 1, 1, 1, method="Nelder-Mead")` – meissner_ Jul 09 '19 at 09:49
  • I have tried that but I got 'minimize() got multiple values for argument 'method'' – TriposG Jul 09 '19 at 09:57
  • Hhm, well that's bad ... i think the a slightly hacky option would be to give the lambda a tuple containing the three variables but i guess that's not the plan here :/ – meissner_ Jul 09 '19 at 10:31

1 Answers1

0

As per documentation of optimize, which was pointed out correctly in this answer, the callable function that's being optimized must accept a tuple of shape (N,), not simply N arguments.

What worked for me was:

ff = lambdify((A,B,C), EL_c)
fff = lambda x: ff(*x) # Unpack tuple into positional args
scipy.optimize.minimize(fff, x0=(1,1,1), method="Nelder-Mead")

(My variables were called A,B,C.)

Misza
  • 635
  • 4
  • 15
  • Thank you for your answer that has worked. By any chance do you know how I could add constraints to limit A,B,C between -1 and 1 ? I used con0=x[0]+1 con1=1-x[0] con2=x[1]+1 con3=1-x[1] con4=x[1]+1 con5=1-x[1] cons = ({'type':'ineq', 'fun': con0},{'type':'ineq', 'fun': con1},{'type':'ineq', 'fun': con2},{'type':'ineq', 'fun': con3},{'type':'ineq', 'fun': con4},{'type':'ineq', 'fun': con5}) – TriposG Jul 09 '19 at 12:44
  • @TriposG Check again the documentation of optimize I linked. For some optimization methods there are ways to specify bounds and/or constraints. – Misza Jul 09 '19 at 12:51