########################################################################
# program: fourier_c.py
# author: Tom Irvine
# Email: tomirvine@aol.com
# version: 1.5
# date: November 10, 2011
# description:  
#    
#  Determine the Fourier transform of a signal.
#  The file must have two columns: time(sec) & amplitude
#  The number of input points should be <= 10000 for speed.
#  Otherwise, an FFT should be used instead.
#
#  The script uses the function fourier_trans compiled by Cython. 
#             
########################################################################

from tompy import read_two_columns,signal_stats,sample_rate_check
from tompy import GetInteger2,WriteData3
from tompy import time_history_plot

from sys import stdin
from math import pi
from numpy import argmax
from numpy import array

import matplotlib.pyplot as plt

import time

import fourier_trans

########################################################################

print " The input file must have two columns: time(sec) & amplitude"

a,b,num =read_two_columns()

sr,dt,mean,sd,rms,skew,kurtosis,dur=signal_stats(a,b,num)

sr,dt=sample_rate_check(a,b,num,sr,dt)

print "\n %d samples \n" %num

########################################################################

numf=float(num)

print " "
print " Remove mean:  1=yes  2=no "

i = GetInteger2()

b=array(b)

if(i==1):
   b-=mean                
   
########################################################################

iflag =0
tpi=2.*pi

ms=0
jk=0
kk=1

df=1./dur

n=num

################################################################################
#

tic=time.time()


ff,zz,ph,f_real,f_imag = fourier_trans.fourier_trans(n,df,b)
 
 
toc=time.time()

ttt= toc-tic
print "\n numerical engine execution time = %g sec \n" %ttt   
 
# 
################################################################################

nhalf=int(float(n)/float(2))
freq=ff
 
idx = argmax(zz) 
    
print " "
print " Maximum:  Freq=%8.4g Hz   Amp=%8.4g " %(ff[idx],zz[idx])

print " "
print "Enter the output Fourier Transform filename (freq, real, imag): "
output_file_path = stdin.readline()
output_file = output_file_path.rstrip('\n')
WriteData3(n,freq,f_real,f_imag,output_file)

print " "
print "Enter the output Fourier Transform filename (freq, mag, phase(rad)): "
output_file_path = stdin.readline()
output_file = output_file_path.rstrip('\n')
WriteData3(nhalf,ff,zz,ph,output_file)

print " "
print " view plots "

time_history_plot(a,b,1,'Time(sec)','Amplitude','Time History','time_history')
     
plt.figure(2)     
plt.plot(ff,zz)
plt.title(' Fourier Magnitude ')
plt.grid(True)
plt.ylabel(' Amplitude ')
plt.xlabel(' Frequency (Hz) ')
plt.savefig('fourier_magnitude')
plt.draw()  

plt.figure(3)
plt.plot(ff,ph*(180./pi))
plt.grid(True)
plt.title(' Fourier Phase ')
plt.ylabel(' Phase (deg) ')
plt.xlabel(' Frequency (Hz) ')
plt.savefig('fourier_phase')
plt.draw()  

plt.show()  