I am attempting to fit a function using Leastsq to fit to a few relevant points in an fft. The issue at hand is that, no matter how good or bad the fit is, there is absolutely no change in the parameters. In other words the least squares takes 6 iterations and does nothing on any of them, then returns the initial parameter values. I cannot determine why nothing is happening.
guess = [per_guess,thresh_guess,cen_guess] #parameter guesses, all real numbers
res, stuff = leastsq(fitting, guess)
The fitting function has a number of manipulations to find the correct indices, which I will not reproduce here to save space, but it returns a list of complex numbers:
M, freq= fft(real_gv, zf)
def fitting(guess):
gi, trial_gv = gen_pat(size, guess[0], guess[1], guess[2])
trial_gv = trial_gv*private.han #apply hanning window
F, freq= fft(trial_gv, zf)
#stuff that picks the right indices
return M[left_fit target:right_fit_target]-F[left_fit target:right_fit_target]
I tried at one point using an array cast in the return, but I would constantly receive errors about casting between complex and real floats, even though I wasn't asking for any. Even with this method, I occasionally receive ComplexWarnings.
EDIT:
As requested, I am putting up gen_pat:
def gen_pat(num, period, threshold, pos = 0, step = 1.0, subdivide=10.0, blur = 1.0):
x= np.arange(-num/2,num/2,step) #grid indexes
j=np.zeros((len(x),subdivide))
for i in range(len(x)):
j[i]=np.linspace(x[i]-0.5*blur,x[i]+0.5*blur,subdivide) #around each discrete point take a subvision. This will be averaged to get the antialiased point. blur allows for underlap (<1) or overlap of pxels
holder = -np.sin(2*np.pi*np.abs(j-pos)/period) #map a sin function for the region
holder = holder < 2.0*threshold-1.0 #map to 1 or 0 based on the fraction of the period that is 0
y = np.sum(holder, axis=1)/float(subdivide) #take the average of the values at the sub-points to get the anti-aliased value at the point i
y= np.array(y)
x= np.array(x)
return x,y
EDIT 2:
Managed to get a fit working using res = fmin_powell(fitting, guess, direc=[[1,0,0],[0,0.1,0],[0,0,1]])
and a modified return. Would still like to know why lestsq didn't work.
return np.sum((M[fit_start_index:fit_end_index].real-F[fit_start_index:fit_end_index].real)**2+(M[fit_start_index:fit_end_index].imag-F[fit_start_index:fit_end_index].imag)**2)