<div dir="ltr"><br><div class="gmail_extra"><br><div class="gmail_quote">On Tue, May 2, 2017 at 9:22 PM, Gideon Simpson <span dir="ltr"><<a href="mailto:gideon.simpson@gmail.com" target="_blank">gideon.simpson@gmail.com</a>></span> wrote:<br><blockquote class="gmail_quote" style="margin:0 0 0 .8ex;border-left:1px #ccc solid;padding-left:1ex">I have a scalar valued function that I’d like to minimize, but, by default, it’s not readily vectorized. In particular, it depends parametrically on the solution of an ODE, and vaguely looks like:<br>
<br>
def f(x, ode_soln):<br>
...<br>
val = spicy.integrate.quad(lambda t: sin(x * t) * ode_soln.sol(t),0,1)<br>
<br>
return val<br>
<br>
By default, if I try to do<br>
<br>
spicy.optimize.minimize(lambda x: f(x,ode_soln))<br>
<br>
I get an error that indicates that minimize thinks f accepts arrays of data. </blockquote><div><br></div><div>minimize() takes two arguments: a callable function that takes an array of values to be adjusted, and an array of starting values. Presumably, `x` is the array of values that you would like optimized, but you have to provide starting values.<br><br></div><div>I don't think you need the lambda, but you might want something like:<br></div><div><br></div><div> scipy.optimize.minimize(f, x0, args=(ode_soln,))<br><br></div><div>where x0 is an array of starting values.<br></div><div> </div><blockquote class="gmail_quote" style="margin:0 0 0 .8ex;border-left:1px #ccc solid;padding-left:1ex"> I can remedy this by writing a little looped version,<br>
<br>
def f_vec(xvec, ode_soln):<br>
fvals = np.zeros_like(xvec)<br>
<br>
for j in range(xvec.size):<br>
fvals[j] = f(xvec[j], ode_soln)<br>
<br>
return fvals<br>
<br>
but I’m wondering if:<br>
<br>
1. Is there a smarter/more elegant solution to handling the vectorized input?<br></blockquote><div><br></div><div>It does handle vectorized input, or perhaps I'm not understanding your question.<br> <br></div><blockquote class="gmail_quote" style="margin:0 0 0 .8ex;border-left:1px #ccc solid;padding-left:1ex">
<br>
2. Is there a way to just tell minimize that it’s going to have to evaluate f one point at a time, rather than writing some other function?<br></blockquote><div><br></div><div>No, or well it depends what you mean by "one point at a time". The objective function provided should take an array of candidate values for the parameters and return either an array to be minimized in the least-squares sense or the scalar cost value.<br><br></div><div>Hope that helps,<br><br></div><div>--Matt <br><br></div></div></div></div>