## Tuesday, April 6, 2010

### How to fit a sine wave – An example in Python

If the frequency of a signal is known, the amplitude, phase, and bias on the signal can be estimated using least-squares regression. The key concept that makes this possible is the fact that a sine wave of arbitrary phase can be represented by the sum of a sin wave and a cosine wave.

The regression problem to find the amplitude and phase is an optimization problem. However,  it is not easily solved when using the amplitude and phase directly. This is because the problem is nonconvex; it has multiple minima.  By applying trigonometric identities, an equivalent problem, which is convex, is formed.

Once the regression problem is in this form, the solution is found by forming linear least squares problem. The python function illustrates how to do this. Since python’s function work in radians but most people prefer Hertz and degrees, this script performs those conversions.

from pylab import *
from math import atan2

def fitSine(tList,yList,freq):
'''
freq in Hz
tList in sec
returns
phase in degrees
'''
b = matrix(yList).T
rows = [ [sin(freq*2*pi*t), cos(freq*2*pi*t), 1] for t in tList]
A = matrix(rows)
(w,residuals,rank,sing_vals) = lstsq(A,b)
phase = atan2(w[1,0],w[0,0])*180/pi
amplitude = norm([w[0,0],w[1,0]],2)
bias = w[2,0]
return (phase,amplitude,bias)

if __name__=='__main__':
import random

tList = arange(0.0,1.0,0.001)
tSamples = arange(0.0,1.0,0.05)
random.seed(0.0)
phase = 65
amplitude = 3
bias = -0.3
frequency = 4
yList = amplitude*sin(tList*frequency*2*pi+phase*pi/180.0)+bias
ySamples = amplitude*sin(tSamples*frequency*2*pi+phase*pi/180.0)+bias
yMeasured = [y+random.normalvariate(0,2) for y in ySamples]
#print yList
(phaseEst,amplitudeEst,biasEst) = fitSine(tSamples,yMeasured,frequency)
print ('Phase estimate = %f, Amplitude estimate = %f, Bias estimate = %f'
% (phaseEst,amplitudeEst,biasEst))

yEst = amplitudeEst*sin(tList*frequency*2*pi+phaseEst*pi/180.0)+biasEst

figure(1)
plot(tList,yList,'b')
plot(tSamples,yMeasured,'+r',markersize=12,markeredgewidth=2)
plot(tList,yEst,'-g')
xlabel('seconds')
legend(['True value','Measured values','Estimated value'])
grid(True)
show()