Problem: I have a set of measurements (time, measurement, error) that exhibit periodic variations and I want to fit them with a Fourier series of the form
where A0 is the mean value of my measurements, t is the time, t0 is a (known) reference time and P is the (known) period. I want to fit for the coefficients A_k and phi_k.
Here is what I've got at the moment:
# Find Fourier components
# nfourier is the number of fourier components
def fourier(coeffs, time_data, epoch, period, nfourier, A0):
import numpy as np
omega = 2.0*np.pi/period
fseries = np.zeros(len(time_data))
fseries.fill(A0)
for k in range(nfourier):
ak = coeffs[k]
phik = coeffs[k+1]
time_diff = time_data - epoch
fseries = fseries + ak * np.cos(k * omega * time_diff + phik)
return fseries
I estimate the residuals as follows:
def residuals(coeffs, measurement_data, time_data, error_data, epoch, period, nfourier, A0):
model = fourier(coeffs, time_data, epoch, period, nfourier, A0)
result = measurement_data - model
return result
Then I fit it with:
def fit_it(coeffs, measurement_data, time_data, error_data, epoch, period, nfourier, A0):
from scipy.optimize import leastsq
opt_coeff = leastsq(residuals, coeffs, args=(measurement_data, time_data, error_data, epoch, period, nfourier, A0))
return opt_coeff
The program completes successfully but the fit seems to fail as can be seen from this figure:
I am not sure what I am doing wrong here but maybe an expert can offer some advice. I would be happy to provide a test dataset if someone is willing to help.