[Tutor] constructing semi-arbitrary functions
"André Walker-Loud <walksloud@gmail.com>"
walksloud at gmail.com
Mon Feb 17 22:18:47 CET 2014
Hi Oscar,
Let me clear up my description of one point - I don’t want to pick on the third party software guys.
> The "right" solution is to change the interface of the third party function. It is poorly designed and should not be inspecting those function attributes or it should at least provide an option for you to provide that information in a different way. Assuming it's open source you could try sending a patch. In the mean time you could copy that code and modify it to suit your purposes.
The issue has to do with making a general polynomial function, not passing the args of a “simple” function. If I define
def f(c_0,c_1):
return chisq(c_0,c_1,x,y,dy)
there is no problem using this function, the variables are all passed correctly.
What I am trying to avoid is having to write a special case for each order of polynomial I want. I tried the following
def poly(x,pars):
val = 0.
for i,ci in enumerate(pars):
val += x**i * ci
return val
def f_lambda(x,pars):
return lambda x,*pars: poly(x,*pars)
x = np.array([1,2,3])
f = f_lambda(x,[-.5,2.])
f(x,[-.5,2.])
array([ 1.5, 3.5, 5.5])
f(x,[-.5,3.])
array([ 2.5, 5.5, 8.5])
etc.
This function correctly gives me a polynomial of arbitrary order, but
f.func_code.co_varnames
('x', 'pars’)
so I can not pass this to the third party minimizer, as it does not know how to interpret ‘pars'. You can probably see trying to replicate the lambda function method for an arbitrary polynomial is what naturally led to the string/exec option.
Thanks,
Andre
More information about the Tutor
mailing list