python - TypeError: 'numpy.ndarray' object is not callable in scipy.optimize leastsq -


i'm new python and, work reason, i'm trying write python code capable read 3 files containing float (x,y) data (let's x1,y1; x2,y2; x3,y3) , combine 2 of arrays (y1 , y2) linear combination approach third (y3) closely possible. moreover, x1 , x2 identical, whereas x3 different, interpolate x3 , y3 using x1. i'm working on idle on mac osx, , python 2.7. here's code:

import numpy np import matplotlib.pyplot plt import tkinter tk import tkfiledialog scipy.optimize import leastsq  root1 = tk.tk() root1.geometry() #window centered on desktop? root1.withdraw() #the main app window doesn't remain in background filename1 = tkfiledialog.askopenfilename(parent=root1, title="ouvrir le spectre n° 1",     filetypes=[('dat files', '.dat'), ('all files', '.*')],     initialdir="/users//science/manips/2011_10_05_nb_w/") filename2 = tkfiledialog.askopenfilename(parent=root1,title="ouvrir le spectre n° 2",     filetypes=[('dat files', '.dat'), ('all files', '.*')],     initialdir="/users/science/manips/2011_10_05_nb_w/") filenameexp = tkfiledialog.askopenfilename(parent=root1, title="ouvrir le spectre exp",     filetypes=[('txt files', '.txt'), ('all files', '.*')],     initialdir="/users/science/manips/2011_10_05_nb_w/spectres_exp")  print 'fichiers choisis = ' print filename1 print filename2 print filenameexp  energy1, spectrum1 = np.loadtxt(filename1, delimiter='   ', usecols=(0, 1),                             unpack=true, skiprows=0) energy2, spectrum2 = np.loadtxt(filename2, delimiter='   ', usecols=(0, 1),                             unpack=true, skiprows=0) energyexp, spectrumexp = np.loadtxt(filenameexp, delimiter='\t', usecols=(0, 1),                             unpack=true, skiprows=0)  #interpolating experimental energy grid on theoretical energy grid sp_exp_int = np.interp(energy1, energyexp, spectrumexp)  #guess contains first guess of parameters  guess=[1.0,1.0] spec_theo = guess[0] * spectrum1 + guess[1] * spectrum2  # errorfunc difference between "fit" , y experimental data errorfunc = spec_theo - sp_exp_int # leastsq finds set of parameters in tuple tpl minimizes # errorfunc=yfit-yexperimental tplfinal, success = leastsq(errorfunc, guess[:], args=(energy1, sp_exp_int)) print "best choice = ", tplfinal  fig, ax1 = plt.subplots() theory = ax1.plot(energy1, spec_theo, 'b-', label='theory') ax1.set_xlabel('energy (ev)') # make y-axis label , match line color. ax1.set_ylabel('theory', color='b')  ax2 = ax1.twinx() experiment = ax2.plot(energy1, sp_exp_int, 'r-', label='experiment') ax2.set_ylabel('experiment', color='r', rotation=-90, labelpad=15)  #one legend axes lns = theory + experiment labs = [l.get_label() l in lns] ax1.legend(lns, labs, loc=0)  plt.show() 

when try run code get:

traceback (most recent call last):  file "/users/science/manips/2011_05_nb_w/mars2016/comblin_leastsquares.py", line 79, in <module> tplfinal, success = leastsq(errorfunc, guess[:], args=(energy1, sp_exp_int)) file   "/opt/local/library/frameworks/python.framework/versions/2.7/lib/python2.7/site- packages/scipy/optimize/minpack.py", line 377, in leastsq shape, dtype = _check_func('leastsq', 'func', func, x0, args, n) file "/opt/local/library/frameworks/python.framework/versions/2.7/lib/python2.7/site-packages/scipy/optimize/minpack.py", line 26, in _check_func res = atleast_1d(thefunc(*((x0[:numinputs],) + args))) typeerror: 'numpy.ndarray' object not callable 

i understand wrong leastsq usage, can't figure out be, knowledge of python insufficient. can me ?

the error states what's wrong: passing array instead of function/callable. in fact leastsq documentation states first argument should callable.

you passing errorfunc first argument not function nor callable. it's array. (it may represent function, isn't in format required leastsq).

so have follow description argument:

should take @ least 1 (possibly length n vector) argument , returns m floating point numbers. must not return nans or fitting might fail.

so replace errorfunc callable given input returns error floats. should have:

def error_func(input):     return input - data 

where data experimental data andinput value of fitting scipy doing. needs callable because perform more iterations , each iteration has compute error in order fit data.

obviously change error_func match doing, give idea of expected leastsq.


Comments