0

So I have some funciton

def fun(x,y=None):
    # Do some stuff

and I want to minimize this function over x, but sometimes I will want to have an additional argument y. (Essentially, I want y to always take its default value, except when I'm minimizing.)

Usually, if the function was just def fun(x,y): I'd be able to do scipy.optimize.minimize(x,args=(y)). But what do I do when y is an optional variable? putting args=(y=value) is giving me invalid syntax, (and, sure, it looks very wrong), but I'm not sure what the correct syntax would be.

I'm using Python 3.7 if that's relevant.

  • This really sounds like you should have two functions. (It's straightforward to solve the `minimize` problem - you use the exact same call you would use if `y` wasn't optional, since optional arguments can still be passed positionally - but the description of how you want to use this function really doesn't sound like a job for 1 function.) – user2357112 Feb 06 '20 at 09:32

1 Answers1

0

You can't. minimize only takes optional arguments without keywords for the function it calls. This is written in the documentation, since it describes the function to be called as fun(x, *args), without any optional arguments.

If your function is f(x, y=None, z=None) you would have to call scipy.optimize.minimize(f, x, (y, z)).

Instead I would construct a lambda that passes the arguments as keywords directly. Thus doing:

scipy.optimize.minimize(lambda x: f(x, z=0), x)

which makes it clear which optional arguments you are passing.

rhaps0dy
  • 1,236
  • 11
  • 13