clear all;
dirin='/Users/atnguyen/DATA/Model/llc1080/aste1080x1260x540x90/run_tides_run2_hourly_it0000_pk0001577880/Mean/';
cd(dirin);

%coriolis param:
f_cor=2*pi/24*2*sin(78.2250*pi/180);	%78.2250 = PointB.lat
T_cor=2*pi/f_cor;			%12.2579;
T_tides=[12.4206 12 12.6583 11.9672 23.9345 25.8193 24.0659 26.8684 6.21 6.10 6.27];%M2 S2 N2 K2 K1 O1 P1 Q1 m4 ms4 mn4

load('PointBcbar_0001577895_0001709280_wet.mat');
N=length(PointB.UVELMASSc_bar);
u=PointB.UVELMASSc_bar'; %[N x 1]
v=PointB.VVELMASSc_bar'; %[N x 1]

signal=u+i.*v;		%[N x 1]

%check what happened if we insists that the signal is odd in length:
%too confusing to sort out neg and pos freq, MAKE SURE SIGNAL IS EVEN

Np=N-1;
signal_odd=signal(1:Np);

dt=1;			%hours per sample
t=(0:dt:N-dt);		%time-series, [0:1:8760-1]

%Frequency specifications:
Fs=1/dt;		%sampling rate, samples per hour, 1/hr
dF=Fs/N;		%sample per Np*dt --> Nyquist Frequency = the smallest deltaF we can resolve, unit 1/hr
f=-Fs/2:dF:Fs/2-dF;	%[1/(2*dt):1/(N*dt):1/(2*dt)-1], unit [1/hr], note it's not cycle/hr

%now take fft:
clear i
U =fft(signal);		%basin fourier transform, U(1:N/2) is the positive f side, U(N/2+1:2*N) is the negative f range
Us=fftshift(U);		%shift the negative side to the left of the positive, so that the f=0 is centered
Usn=Us./sqrt(N);	%normalized by the length of record, such that when plot as power = abs(Usn.^2) it's normalized by N.

ineg_fft=1:N/2;ipos_fft=N/2+1:N; 	%ineg_fft is an odd number, ipos_fft , which contains the f=0 as first entry, is even number
[f(ineg_fft(1)) f(ineg_fft(end)) f(ipos_fft(1)) f(ipos_fft(end))]	%[-0.5000   -0.0001 0    0.4999];%note not symmetric yet..
%if want to really get right, likely have to define f as: f=-Fs/2+dF/2:Fs:Fs/2-dF/2: yes! 
%[fp(ineg_fft(1)) fp(ineg_fft(end)) fp(ipos_fft(1)) fp(ipos_fft(end))] = [-0.4999   -0.0001    0.0001    0.4999]
%i_DC=ceil(Np/2);if(f(i_DC)<0);f(i_DC)=0;end;	%STILL NEED TO VERIFY; f(i_DC-1:i_DC+1)=-1e-4 , if signal is even, there shouldn't be the i_DC?
figure(1);clf;loglog(abs(f(ineg_fft)),abs(Usn(ineg_fft)).^2,'b-');grid;hold on;loglog(f(ipos_fft),abs(Usn(ipos_fft)).^2,'r-');
loglog([1/T_cor 1/T_cor],[1e-10 1e3],'g-');loglog([1/T_tides(1) 1/T_tides(1)],[1e-10 1e3],'m-');
loglog([1/T_tides(2) 1/T_tides(2)],[1e-10 1e3],'k-');loglog([1/T_tides(4) 1/T_tides(4)],[1e-10 1e3],'-','color',.6.*[1 1 1]);
loglog([1/T_tides(5) 1/T_tides(5)],[1e-10 1e3],'y-');loglog([1/T_tides(9) 1/T_tides(9)],[1e-10 1e3],'c-');hold off;
legend('neg f','pos f','inertial','M2','S2','K2','K1','m4');xlabel('frequency [1/hr, not cycle/yr]');ylabel('Power m^2/s^2');

%now do my own fft to see if i can see clearer the pos and neg spectra, and also to check magnitudes
tt=[0:dt:N-dt]';          %[N 1]

clear SS* jpos* jneg* ff* freq
clear i j
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%make sure signal is ODD in length:
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  clear j ineg ipos  Xreal Ximag freq temp tempf
%make sure the dimension to perform fft is 1st:
  Finf=signal_odd;          %[N-1 x 1]
  tt1=tt(1:end-1);
  [Xreal,Ximag,Fmean,tempf,freq,ipos,ineg]=forward_fft(Finf,tt1);imid=ineg(end)+1;  %[N l]
  SSf0=tempf;	%Nx1

  figure(4);clf;
  loglog(abs(freq(ineg))',SSf0(ineg,:)./(N-1),'b-',...
             freq(ipos)', SSf0(ipos,:)./(N-1),'r-','linewidth',1.5);grid;
  aa=axis;yy=[aa(3) aa(4)];
  %plot([f0 f0],yy,'k-','linewidth',1.5);
  %plot([ft1(2) ft1(2)],yy,'-','color','g','linewidth',1.5);
  %%plot([ft1(3) ft1(3)],yy,'-','color','m','linewidth',2);
  %plot([fN(2) fN(2)].*pi/(2*pi),yy,'-','color',[.7,.7,.7],'linewidth',3);
  %plot([fN(3) fN(3)].*pi/(2*pi),yy,'-','color',[.7,.7,.7],'linewidth',3);
  %for k=[1,4:8];plot([ft1(k) ft1(k)],yy,'c--');end;hold off;

  legend('f-o cw','f+o ccw','f-bp cw','f+bp ccw',...
         'f0',['f\_' tidename1{2}],'Location','NorthWest');%['f\_' tidename1{3}],1);
  set(gca,'Xtick',1./[27:-1:4],'Xticklabel',27:-1:4);%axis([1/18 1/7 aa(3) aa(4)]);
  xlabel('period [hr]');ylabel('power spectrum [m^2/s^4]');%<-- need to verify the unit!!
  title(['Full series, z(klev=' num2str(klev) ')=' num2str(round(rc(klev))) 'm']);

%now plotting first result and this on top of each other:
figure(5);clf;
subplot(121);
loglog(abs(f(ineg_fft)),abs(Usn(ineg_fft)).^2,'b-');grid;hold on;loglog(abs(freq(ineg))',SSf0(ineg,:)./N,'r-');
loglog([1/T_cor 1/T_cor],[1e-10 1e3],'g-');loglog([1/T_tides(1) 1/T_tides(1)],[1e-10 1e3],'m-');
loglog([1/T_tides(2) 1/T_tides(2)],[1e-10 1e3],'k-');loglog([1/T_tides(4) 1/T_tides(4)],[1e-10 1e3],'-','color',.6.*[1 1 1]);
loglog([1/T_tides(5) 1/T_tides(5)],[1e-10 1e3],'y-');loglog([1/T_tides(9) 1/T_tides(9)],[1e-10 1e3],'c-');hold off;
legend('neg f,fft','neg f,atnfft','inertial','M2','S2','K2','K1','m4','location','southwest');
xlabel('frequency [1/hr, not cycle/yr]');ylabel('Power (m^2/s^2/)hr^2');
subplot(122);
loglog(f(ipos_fft),abs(Usn(ipos_fft)).^2,'b-');grid;hold on;loglog(freq(ipos)', SSf0(ipos,:)./N,'r-');
loglog([1/T_cor 1/T_cor],[1e-10 1e3],'g-');loglog([1/T_tides(1) 1/T_tides(1)],[1e-10 1e3],'m-');
loglog([1/T_tides(2) 1/T_tides(2)],[1e-10 1e3],'k-');loglog([1/T_tides(4) 1/T_tides(4)],[1e-10 1e3],'-','color',.6.*[1 1 1]);
loglog([1/T_tides(5) 1/T_tides(5)],[1e-10 1e3],'y-');loglog([1/T_tides(9) 1/T_tides(9)],[1e-10 1e3],'c-');hold off;
legend('pos f,fft','pos f,atnfft','inertial','M2','S2','K2','K1','m4','location','southwest');
xlabel('frequency [1/hr, not cycle/yr]');ylabel('Power (m^2/s^2/)hr^2');

%so: all spectra are of the same magnitude once both are normalized by N.
%Lastly, not sure why my fft has more "signal" between 10^-1 to 10^0 range.

%now, get the syntax for the periodogram, to see what range and unit they are
[Pw,fw]=pmtm(signal);
[Pwa,fwa]=periodogram(signal);
%so these fwa are truly cycle/hr, to get 1/hr, need to div fwa by (2*pi)
%if we want to plot w/ respect to fwa/(2*pi) instead of fwa, need to also
%remove the factor (2*pi)^2 from Pw in the plot
%Lastly, there are "bogus" signals at larger frequency that the maximum we can resolve, which is dt/2
%so, should make a cut off to avoid the "noise" at freq > dt/2:
ij=find(fwa./(2*pi)<(dt/2));
figure(2);clf;
     %loglog(1./(fwa./(2*pi)),Pwa.*(2*pi).^2,'b-',1./(fw./(2*pi)),Pw.*(2*pi).^2,'r-');grid;
     loglog(fwa(ij)./2/pi,Pwa(ij),'b-',fw(ij)./2/pi,Pw(ij),'r-');grid;
     hold on;loglog([1/12 1/12],[1e-10 1e1],'g-');
             loglog([1/24 1/24],[1e-10 1e1],'m-');hold off;
     xlabel('frequency 1/hr');%xlabel('Period in hours');
     ylabel('Spectral density, [(m^2/s^2) / hr^2]');
     %set(gca,'Xlim',[2 10^(5.5)],'Ylim',[1e-12 1.1e2]);
     %text(24.6,1e2,'24 hr');text(12.3,1e2,'12 hr');

%plot all 3 on top:
%now plotting first result and this on top of each other: seems like i need a 2*pi (not (2*pi)^2) to match magnitude.. not sure
%how these were obtained, so best to rely on the Fourier transform and take abs().^2/N
figure(5);clf;
subplot(121);
loglog(abs(f(ineg_fft)),abs(Usn(ineg_fft)).^2,'b-');grid;hold on;loglog(abs(freq(ineg))',SSf0(ineg,:)./N,'r-');
loglog([1/T_cor 1/T_cor],[1e-10 1e3],'-','color',[.2 .5 .8]);loglog([1/T_tides(1) 1/T_tides(1)],[1e-10 1e3],'m-');
loglog([1/T_tides(2) 1/T_tides(2)],[1e-10 1e3],'k-');loglog([1/T_tides(4) 1/T_tides(4)],[1e-10 1e3],'-','color',.6.*[1 1 1]);
loglog([1/T_tides(5) 1/T_tides(5)],[1e-10 1e3],'y-');loglog([1/T_tides(9) 1/T_tides(9)],[1e-10 1e3],'c-');hold off;
legend('neg f,fft','neg f,atnfft','inertial','M2','S2','K2','K1','m4','location','southwest');
xlabel('frequency [1/hr, not cycle/yr]');ylabel('Power (m^2/s^2/)hr^2');
subplot(122);
loglog(f(ipos_fft),abs(Usn(ipos_fft)).^2,'b-');grid;hold on;loglog(freq(ipos)', SSf0(ipos,:)./N,'r-');loglog(fwa(ij)./2/pi,Pwa(ij)*2*pi,'g-');
loglog([1/T_cor 1/T_cor],[1e-10 1e3],'-','color',[.2 .5 .8]);loglog([1/T_tides(1) 1/T_tides(1)],[1e-10 1e3],'m-');
loglog([1/T_tides(2) 1/T_tides(2)],[1e-10 1e3],'k-');loglog([1/T_tides(4) 1/T_tides(4)],[1e-10 1e3],'-','color',.6.*[1 1 1]);
loglog([1/T_tides(5) 1/T_tides(5)],[1e-10 1e3],'y-');loglog([1/T_tides(9) 1/T_tides(9)],[1e-10 1e3],'c-');hold off;
legend('pos f,fft','pos f,atnfft','pos f, periodogram','inertial','M2','S2','K2','K1','m4','location','southwest');
xlabel('frequency [1/hr, not cycle/yr]');ylabel('Power (m^2/s^2/)hr^2');

%NOW, do bandpass filter
%------- design band pass filter --------------------
%inertial period: ~12hr , so filter 9hr to 16hr (8-19)
Omega0=2*pi/(23+56/60+4.1/3600)		%radian/hr, earth rotation rate
f0=2*Omega0*sin(PointB.Lat*pi/180)/(2*pi);%take radian out, 1/hr, = 0.0797823
T0=1/f0;				%12.2245 [hr] , compared to T_cor=12.2579
% [Fstop1,Fpass1,Fpass2,Fstop2,dB_left,dB_center,dB_right] 
% [2*pi/18hr/pi,2*pi/4hr/pi,2*pi/8hr/pi,2*pi/18hr/pi,-60dB,1dB,-60dB]
TN=[17,15,9,7];
fN=2.*pi/pi./TN;	%<-- Normalized by pi, has 2*pi in it, so this is (2*pi/T)/pi
d=fdesign.bandpass('Fst1,Fp1,Fp2,Fst2,Ast1,Ap,Ast2',fN(1),fN(2),fN(3),fN(4),60,1,60);
Hd4=design(d,'cheby2');fvtool(Hd4);	%note 16.Sep.2016: fvtool works only with matlab2013a, not matlab2012b
hold on;plot([2*pi*f0/pi 2*pi*f0./pi],[-65 5],'k-');hold off;	%<-- plot f0 on top
strT3=sprintf('%2.2i',TN(3)); strT2=sprintf('%2.2i',TN(2));

%filter:
clear i j
signal_filter=filter(Hd4,real(signal))+i.*filter(Hd4,imag(signal));
Uf =fft(signal_filter);	%basin fourier transform, U(1:N/2) is the positive f side, U(N/2+1:2*N) is the negative f range
Ufs=fftshift(Uf);	%shift the negative side to the left of the positive, so that the f=0 is centered
Ufsn=Ufs./sqrt(N);	%normalized by the length of record, such that when plot as power = abs(Usn.^2) it's normalized by N.

%now plotting filtered result and on top of raw signal
figure(5);clf;
subplot(121);
loglog(abs(f(ineg_fft)),abs(Usn(ineg_fft)).^2,'b-');grid;hold on;loglog(abs(freq(ineg))',SSf0(ineg,:)./N,'g-');
loglog(abs(f(ineg_fft)),abs(Ufsn(ineg_fft)).^2,'r-');
loglog([1/T_cor 1/T_cor],[1e-10 1e-1],':','color',[.5 .2 .8]);loglog([1/T_tides(1) 1/T_tides(1)],[1e-10 1e-1],'m:');
loglog([1/T_tides(2) 1/T_tides(2)],[1e-10 1e-1],'k:');loglog([1/T_tides(4) 1/T_tides(4)],[1e-10 1e-1],':','color',.6.*[1 1 1]);
loglog([1/T_tides(5) 1/T_tides(5)],[1e-10 1e-1],'y:');loglog([1/T_tides(9) 1/T_tides(9)],[1e-10 1e-1],'c:');hold off;
legend('neg f,fft','neg f,atnfft','neg f, bp 9-15hr','inertial','M2','S2','K2','K1','m4','location','southwest');
xlabel('frequency [1/hr, not cycle/yr]');ylabel('Power (m^2/s^2/)hr^2');set(gca,'ylim',[1e-12 1e-1],'xlim',[1e-2 .5]);
subplot(122);
loglog(f(ipos_fft),abs(Usn(ipos_fft)).^2,'b-');grid;hold on;loglog(freq(ipos)', SSf0(ipos,:)./N,'g-');
loglog(f(ipos_fft),abs(Ufsn(ipos_fft)).^2,'r-');
loglog([1/T_cor 1/T_cor],[1e-10 1e-1],':','color',[.5 .2 .8]);loglog([1/T_tides(1) 1/T_tides(1)],[1e-10 1e-1],'m:');
loglog([1/T_tides(2) 1/T_tides(2)],[1e-10 1e-1],'k:');loglog([1/T_tides(4) 1/T_tides(4)],[1e-10 1e-1],':','color',.6.*[1 1 1]);
loglog([1/T_tides(5) 1/T_tides(5)],[1e-10 1e-1],'y:');loglog([1/T_tides(9) 1/T_tides(9)],[1e-10 1e-1],'c:');hold off;
legend('pos f,fft','pos f,atnfft','pos f, bp 9-15hr','inertial','M2','S2','K2','K1','m4','location','southwest');
xlabel('frequency [1/hr, not cycle/yr]');ylabel('Power (m^2/s^2/)hr^2');set(gca,'ylim',[1e-12 1e-1],'xlim',[1e-2 .5]);

%lastly: attempt to get a "smoother" spectrum by cutting original signals into chunks and then taking avg.
%use 10-mo records, will do a "sliding window of every 24hrs" to obtain
N1=30*24*10;	%10mo, 30-day = 720 -> 7200 records
Fs1=1/dt;		%sampling rate, samples per hour, 1/hr
dF1=Fs1/N1;		%sample per Np*dt --> Nyquist Frequency = the smallest deltaF we can resolve, unit 1/hr
f1=-Fs1/2:dF1:Fs1/2-dF1;%[1/(2*dt):1/(N*dt):1/(2*dt)-1], unit [1/hr], note it's not cycle/hr
ineg_fft1=1:N1/2;ipos_fft1=N1/2+1:N1; 	%ineg_fft is an odd number, ipos_fft , which contains the f=0 as first entry, is even number

nchunks=(N-N1)/24+1;
Uchunk=zeros(N1,nchunks);

for k=1:nchunks;	%65 chunks
  i0=(k-1)*24+1;
  ii=i0:i0+N1-1;
  Uchunk(:,k)=fftshift(fft(signal(ii)))./sqrt(N1);
end;
%now plotting filtered result and on top of raw signal
Uchunk_meansq=mean(abs(Uchunk).^2,2);
figure(5);clf;
subplot(121);
loglog(abs(f(ineg_fft)),abs(Usn(ineg_fft)).^2,'b-');grid;hold on;loglog(abs(freq(ineg))',SSf0(ineg,:)./N,'g-');
loglog(abs(f1(ineg_fft1)),Uchunk_meansq(ineg_fft1),'r-');
loglog([1/T_cor 1/T_cor],[1e-10 1e-1],':','color',[.5 .2 .8]);loglog([1/T_tides(1) 1/T_tides(1)],[1e-10 1e-1],'m:');
loglog([1/T_tides(2) 1/T_tides(2)],[1e-10 1e-1],'k:');loglog([1/T_tides(4) 1/T_tides(4)],[1e-10 1e-1],':','color',.6.*[1 1 1]);
loglog([1/T_tides(5) 1/T_tides(5)],[1e-10 1e-1],'y:');loglog([1/T_tides(9) 1/T_tides(9)],[1e-10 1e-1],'c:');hold off;
legend('neg f,fft','neg f,atnfft','neg f, mean','inertial','M2','S2','K2','K1','m4','location','southwest');
xlabel('frequency [1/hr, not cycle/yr]');ylabel('Power (m^2/s^2/)hr^2');set(gca,'ylim',[1e-12 1e-1],'xlim',[1e-2 .5]);
subplot(122);
loglog(f(ipos_fft),abs(Usn(ipos_fft)).^2,'b-');grid;hold on;loglog(freq(ipos)', SSf0(ipos,:)./N,'g-');
loglog(abs(f1(ipos_fft1)),Uchunk_meansq(ipos_fft1),'r-');
loglog([1/T_cor 1/T_cor],[1e-10 1e-1],':','color',[.5 .2 .8]);loglog([1/T_tides(1) 1/T_tides(1)],[1e-10 1e-1],'m:');
loglog([1/T_tides(2) 1/T_tides(2)],[1e-10 1e-1],'k:');loglog([1/T_tides(4) 1/T_tides(4)],[1e-10 1e-1],':','color',.6.*[1 1 1]);
loglog([1/T_tides(5) 1/T_tides(5)],[1e-10 1e-1],'y:');loglog([1/T_tides(9) 1/T_tides(9)],[1e-10 1e-1],'c:');hold off;
legend('pos f,fft','pos f,atnfft','pos f, mean','inertial','M2','S2','K2','K1','m4','location','southwest');
xlabel('frequency [1/hr, not cycle/yr]');ylabel('Power (m^2/s^2/)hr^2');set(gca,'ylim',[1e-12 1e-1],'xlim',[1e-2 .5]);
