On Mon, Aug 2, 2010 at 3:35 PM, Alex Kraus <[email protected]> wrote: > > Hi, > > I am trying to create a function that calculates the integral of another > function. The integral function should later be used in > scipy.optimize.leastsq(f, ...), so ideally it should have the format: > > def f(x, *param) > > so that it works for a variable number of parameters. While my code works for > a fixed number of parameters I cannot get it to work with a variable number > of parameters. It seems that numpy.vectorize fails here. > > Is there a different/better way to do this? > > from scipy.integrate import quad > import numpy as np > > def integrand_function(x, a, b, c): > result = a*x**2 + np.exp(b*x) + np.cos(a*c) > return result > > def define_integral(f, lower, upper): > assert(lower < upper) > > def function(a, b, c): > result = quad(f, lower, upper, args=(a, b, c))[0] > return result > return np.vectorize(function) > > def integrand_function_param(x, *param): > a, b, c = param > result = a*x**2 + np.exp(b*x) + np.cos(a*c) > return result > > def define_integral_param(f, lower, upper): > assert(lower < upper) > > def function(a, *param): > print(param) > result = quad(f, lower, upper, args=(a, param))[0] > return result > return np.vectorize(function) > > a = np.array([1,2,3,4]) > > print(integrand_function(1,2,3,4)) > # 21.9400368894 > > f = define_integral(integrand_function, 0.0, 2.0) > print(f(a, 1,2)) > # [ 8.22342909 10.41510219 16.30939667 16.7647227 ] > > print(integrand_function_param(1,2,3,4)) > # 21.9400368894 > > fp = define_integral_param(integrand_function_param, 0.0, 2.0) > print(fp(a, 1,2)) > # ValueError: mismatch between python function inputs and received arguments
vectorize cannot infer correctly the number of arguments with *params see http://projects.scipy.org/scipy/ticket/422 the solution that I used in scipy.stats.distributions was to explicitly specify the number of input arguments. nin = ... (I don't remember all the details) Josef > > # fp should later be used in scipy.optimize.leastsq(fp, ... > > Any help is very appreciated! > Alexander > > > _______________________________________________ > NumPy-Discussion mailing list > [email protected] > http://mail.scipy.org/mailman/listinfo/numpy-discussion > _______________________________________________ NumPy-Discussion mailing list [email protected] http://mail.scipy.org/mailman/listinfo/numpy-discussion
