%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

% source: https://mspace.lib.umanitoba.ca/handle/1993/4453?show=full
% http://dx.doi.org/10.5203/ds_bib_3

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Hybrid despiking method 
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Written by Amir Hossein Birjandi June 2010
% University of Manitoba
% Department of mechanical and Manufacturing Engineering
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% The present code removes high amplitude spikes form the Acoustic Dopple Velocimetry (ADV)
% signal or any other signals and replace them by a linear interpolation between two contiguous 
% valid data points. The advantage of this method is its accuracy in dealing with highly contaminated signals.
% This method removes high amplitude spikes in two steps. In the first step spikes with high a deviation from the mean 
% value are removed by the thresholding and acceleration mothods. In the
% second step spikes and abnormal data points with a low deviation from the
% mean vale are explored. Removed data points are replaced by a linear
% interpolation between two contiguous valid data points. 
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% this code was modified mildly by Marcus Klaus, Swedish University of Agricultural Sciences (SLU), Umeå, Sweden
% to adjust directories and filtering strength parameters
% contact: marcus.klaus@slu.se
% last update: 2026/05/13
%


currentDir = fileparts(currentFile);
targetDir = fullfile(currentDir, '..', '..', ...
    'Data', 'Rawdata', 'ADV');

cd(targetDir)

% select only dat.files not despiked yet
filenames = dir('*.dat');
names = {filenames.name};
notDespike  = ~contains(names, 'despike');  
filenames = filenames(notDespike);

%select filtering strength (Klaus et al. 2019, Listening to air–water gas exchange in running waters, L&O Methods: Volume17, Issue7,  https://doi.org/10.1002/lom3.10321)

acths = 1.8
acfas = 2.5


    % loop through all files in folder
    %for k=1:1:length(filenames)
    for k=1:1:length(filenames)
        %for k=ks

        %Read the input data file
        %Insert your file name here
        [data]=textread(filenames(k).name);
        fs=64;          % Sampling frequency
        t=1:size(data,1);     %Time series
        tb=1;            % Begin time index
        te=round(length(t));    % End time index

        %Velocity vectors
        U_x=data(tb:te,3);
        U_y=data(tb:te,4);
        U_z=data(tb:te,5);
        %Fluctuating velocities
        u_x=U_x-mean(U_x);
        u_y=U_y-mean(U_y);
        u_z=U_z-mean(U_z);
        %Correlation vectors
        C_x=data(tb:te,12);
        C_y=data(tb:te,13);
        C_z=data(tb:te,14);
        C_x_new=C_x;
        C_y_new=C_y;
        C_z_new=C_z;
        %SNR vectors
        S_x=data(tb:te,9);
        S_y=data(tb:te,10);
        S_z=data(tb:te,11);
        S_x_new=S_x;
        S_y_new=S_y;
        S_z_new=S_z;

        %Plot the original signal
        %U1=U_x;
        %figure(1);
        %plot(t,U_x);




        %   Despiking on all 3 velocity components
        for i=1:1:3
            % Velocity vectors (u, v, w)
            U1=data(tb:te,i+2);
            % Fluctuations
            u1=U1-mean(U1);
            u_prime=u1;
            tshift=t-t(1);   % shifted time series (starts from zero)

            %figure(1)
            %plot(tshift,u1,'b*')
            %hold on

            %      %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
            %      Hybrid despiking method
            %      If your signal contains high amplitude spikes it may affect your
            %      statistics. So before any further calculation you require to remove
            %      spikes from your signal. For that perpose we offer the Hybrid despiiking method here.
            %      %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
            %despiking = input('Do you want to despike your signal? y/n [y]: ', 's');
            %if isempty(despiking)
            %    despiking = 'y';
            %end
            %if despiking=='y'
            uxnew1=u_prime; % Stores the valid data points
            u_spike=zeros(length(u_prime),1);% Stores the spikes
            %             %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
            %             Threshold filtering
            %              This method filtes high amplitude spikes
            %             %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
            %T_filter = input('Do you want to use the thresholding filtering method first? y/n [y]: ', 's');
            %if isempty(T_filter)
            %    T_filter = 'y';
            %end
            %if T_filter=='y'
            %V_threshold = input('Please enter the the velocity threshold [3*std]: ');
            %if isempty(V_threshold)
            V_threshold = 3*std(u1); % defult for velocity threshold is 3*std
            %end
            u_spike=((abs(u_prime)>=V_threshold)) .*u1+u_spike;% Filters points beyond the threshold
            u_prime=(abs(u_prime)<V_threshold) .*u_prime;% keeps valid points
            [r,c,uxnew1]=find(u_prime);

            u_prime=u_prime-(u_prime ~=0).*mean(uxnew1);% Removes the mean value from the filtered dataset.
            %               %%%%%%%%%%%%%%%%%%%
            %               % Frist and the last point of u_prime must be non zero.
            %               %Otherwise error occurs
            %               %%%%%%%%%%%%%%%%%%%
            if u_prime(length(u1))==0
                u_prime(length(u1))=u1(length(u1));
            end
            if u_prime(1)==0
                u_prime(1)=u1(1);
            end
            [r,c,uxnew1]=find(u_prime); % uxnew1 is the new dataset vector
            [r2,c2,uxnew2]=find((u_prime ~=0).*(u1-u_prime));
            s_dif=mean(uxnew2);
            uxnewi=r(1):1:r(length(r));      %Generates evenly distributed numbers from 1 to the length of the signal
            uxnewj=interp1(r,uxnew1,uxnewi); % Linear interpolation between valid data points to replace spikes
            %                 uxnew1=uxnewj;
            [rr,cc,u_spike2]=find(u_spike);
            %    figure(2)
            %    plot(tshift,u1,'b*')
            %    hold on
            %    plot(tshift(rr),u1(rr),'rO')
            %    hold on
            %    plot(tshift(rr),uxnewj(rr)+s_dif,'r*')
            %end
            %           %%%%%%%%%%%%%%%%%%%%%%%%%%%%%
            %           %This section removes the spikes with high/low accelerations and far from
            %           %the mean vale
            %           %%%%%%%%%%%%%%%%%%%%%%%%%%%%%
            %acth=input('Please enter the search domain threshold, a number between 1.5 and 4 [defult=3 if enter nothing]: ');
            %if isempty(acth) 
            acth = acths;
            %end
            %acfa=input('Please enter a value for acceleration factor, a number between 2 and 10 [defult=5 if enter nothing]: ');
            %if isempty(acfa)  
            acfa = acfas;
            %end
            n_spikes=length(u_prime);% Initial value for number of spikes which is a stop criteria
            niter=0;   %Number of itterations
            while (n_spikes>(0.0001*length(u_prime)))
                niter=niter+1;
                n_spikes=length(uxnew1);
                u_x2=circshift(u_prime,[-1,0]);
                du_x=(u_x2-u_prime).*fs;  %Acceleration (first derivative of the signal)
                threshold=acth*std(uxnew1); %Filtering threshold
                %%%%%%%%%%%%%%%%%%%%
                %Despiking criteria
                %%%%%%%%%%%%%%%%%%%%
                u_spike=((abs(u_prime)>=threshold & abs(du_x)>=(acfa*9.81))) .*u1+u_spike;
                u_prime=(abs(u_prime)<threshold | abs(du_x)<(acfa*9.81)) .*u_prime;
                [r,c,uxnew1]=find(u_prime);
                u_prime=u_prime-(u_prime ~=0).*mean(uxnew1);% Removes the mean value from the despiked dataset
                [r,c,uxnew1]=find(u_prime); % uxnew1 is the new clean dataset vector
                n_spikes=n_spikes-length(uxnew1);
            end
            [r2,c2,uxnew2]=find((u_prime ~=0).*(u1-u_prime));
            s_dif=mean(uxnew2);
            if u_prime(length(u1))==0
                u_prime(length(u1))=u1(length(u1));
            end
            if u_prime(1)==0
                u_prime(1)=u1(1);
            end
            [r,c,uxnew1]=find(u_prime);   %Valid data points vector
            uxnewi=r(1):1:r(length(r));      %Generates evenly distributed numbers from 1 to the length of the signal
            uxnewj=interp1(r,uxnew1,uxnewi); % Linear interpolation between valid data points to replace spikes
            [rr,cc,u_spike2]=find(u_spike);
            %figure(3)
            %plot(tshift,u1,'b*')
            %hold on
            %plot(tshift(rr),u1(rr),'rO')
            %hold on
            %plot(tshift(rr),uxnewj(rr)+s_dif,'r*')
            %           %%%%%%%%%%%%%%%%%%%%%%%
            %           %This section removes the rest of the high amplitude spikes and searchs
            %           %the signal for the low amplitude spikes as well.
            %           %%%%%%%%%%%%%%%%%%%%%%%
            n_spikes=length(u_prime);
            uxnew1=u_prime;
            ta=1;
            while (n_spikes>(0.0001*length(u_prime)) & ta<5) 
                n_spikes=length(uxnew1);
                %First derivative
                u_x2=circshift(u_prime,[-1,0]);
                u_x3=circshift(u_prime,[1,0]);
                du_x=(u_x2-u_x3)/2;     %First derivative
                %Second derivative
                du_x2=circshift(du_x,[-1,0]);
                du_x3=circshift(du_x,[1,0]);
                ddu_x=(du_x2-du_x3)/2;      %Second derivative
                lambda=sqrt(2*log(length(u_prime)));  %   Universal threshold
                %Principal axes and rotation angle
                teta=atan(sum((u_prime-mean(u_prime)).*ddu_x)/sum((u_prime-mean(u_prime)).^2));   % Rotation angle
                e1=lambda*std(u_prime);  % Primcipal axis in u-du plane
                e2=lambda*std(du_x);       % Primcipal axis in u-du and du-ddu planes
                e3=lambda*std(ddu_x);      % Primcipal axis in du-ddu plane
                e4=sqrt(((lambda*std(u_prime)*cos(teta))^2-(lambda*std(ddu_x)*sin(teta))^2)/((cos(teta))^4-(sin(teta))^4)); % Primcipal axis in u-ddu plane
                e5=sqrt(((lambda*std(ddu_x)*cos(teta))^2-(lambda*std(u_prime)*sin(teta))^2)/((cos(teta))^4-(sin(teta))^4)); % Primcipal axis in u-ddu plane
                u_x22=u_prime.*cos(teta)+ddu_x.*sin(teta);       % Rotates the data by theta
                ddu_x22=ddu_x.*cos(teta)-u_prime.*sin(teta);     % Rotates the data by theta

                %If you want to see the filtering ellipsoids you can activate this
                %section
                %Plot the ellipses and filter the outside points
                %%%%%%%%%%%%
                %u-du plane
                %%%%%%%%%%%%
                [r1,c1,filter1]=find((((u_prime-mean(u_prime)).^2)/e1^2+((du_x).^2)/e2^2-1)>0); % detect spikes
                %Filtering ellipse
                xc = mean(u_prime);  yc = mean(du_x);
                tt = 0:pi/200:2*pi;
                xu = e1*cos(tt);
                yv = e2*sin(tt);
                %figure(5)
                %plot(xu+xc,yv+yc) % plot the filtering ellipse
                %hold on
                %plot(u_prime,du_x,'b*') % plot the whole dataset
                %hold on
                %plot(u_prime(r1),du_x(r1),'rO') % plot the spikes

                %%%%%%%%%%%%
                %du-ddu plane
                %%%%%%%%%%%%
                [r2,c2,filter2]=find(((du_x).^2/e2^2+(ddu_x).^2/e3^2-1)>0);  % detect spikes
                %Filtering ellipse
                xc = 0;  yc = 0;
                tt = 0:pi/200:2*pi;
                xu = e2*cos(tt);
                yv = e3*sin(tt);
                %figure(6)
                %plot(xu,yv)% plot the filtering ellipse
                %hold on
                %plot(du_x,ddu_x,'b*') % plot the whole dataset
                %hold on
                %plot(du_x(r2),ddu_x(r2),'rO')% plot the spikes

                %%%%%%%%%%%%
                %u-ddu plane
                %%%%%%%%%%%%

                [r3,c3,filter3]=find(((u_x22).^2/e4^2+(ddu_x22).^2/e5^2-1)>0); % detect spikes
                %Filtering ellipse
                xc = 0;  yc = 0;
                tt = 0:pi/200:2*pi;
                xu = e4*cos(tt);
                yv = e5*sin(tt);
                xx = xu*cos(teta) - yv*sin(teta);
                yy = xu*sin(teta) + yv*cos(teta);
                x = xc + xx;
                y = yc + yy;
                figure(7)
                plot(x,y)% plot the filtering ellipse
                hold on
                plot(u_prime,ddu_x,'b*') % plot the whole dataset
                hold on
                plot(u_prime(r3),ddu_x(r3),'rO')% plot the spikes

                %              %%%%%%%%%%%%%%%%%%%%%%
                %              Filtering criteria
                %              %%%%%%%%%%%%%%%%%%%%%%
                u_spike=(((u_prime).^2/e1^2+(du_x).^2/e2^2-1)>0 | ((du_x).^2/e2^2+(ddu_x).^2/e3^2-1)>0 | ((u_x22).^2/e4^2+(ddu_x22).^2/e5^2-1)>0).*u1+u_spike;
                u_prime=(((u_prime).^2/e1^2+(du_x).^2/e2^2-1)<0 & ((du_x).^2/e2^2+(ddu_x).^2/e3^2-1)<0 & ((u_x22).^2/e4^2+(ddu_x22).^2/e5^2-1)<0).*u_prime;
                [r,c,uxnew1]=find(u_prime);
                u_prime=u_prime-(u_prime ~=0).*mean(uxnew1); % Removes the mean value
                [r,c,uxnew1]=find(u_prime); % uxnew1 is a vector of  clean data points
                n_spikes=n_spikes-length(uxnew1);
                ta=ta+1;
            end
            [r2,c2,uxnew2]=find((u_prime ~=0).*(u1-u_prime));
            s_dif=mean(uxnew2);
            if u_prime(length(u1))==0
                u_prime(length(u1))=u1(length(u1));
            end
            if u_prime(1)==0
                u_prime(1)=u1(1);
            end
            [r,c,uxnew1]=find(u_prime);   %Valid data points vector
            uxnewi=r(1):1:r(length(r));     %Evenly distributed vector from 1 to the length of the signal
            uxnewj=interp1(r,uxnew1,uxnewi);% Linear interpolation to replace spikes
            u_prime=transpose(uxnewj)+s_dif;    %Filtered data points
            [r3,c3,u_spike]=find(u_spike);
            u_spike=transpose(u_spike);     %Spikes vector
            %figure(4)
            %plot(tshift,u1,'b*')
            %hold on
            %plot(tshift(r3),u1(r3),'rO')
            %hold on
            %plot(tshift(r3),u_prime(r3),'r*')
            %figure(5)
            %plot(tshift,u_prime,'r*')
            %hold on
            %plot(tshift,u1,'b*')
            %end
            %%%%%%%%%%%%%%%%%%%
            %Write the new value
            %%%%%%%%%%%%%%%%%%%
            if i==1
                u_x=u1;
                U_x=U1;
                u_x_new=u_prime;
                U_x_new=u_x_new+mean(U1);
                %figure(6)
                %plot(tshift,U_x,'b*')
                %hold on
                %plot(tshift,U_x_new,'r*')
            end
            if i==2
                u_y=u1;
                U_y=U1;
                u_y_new=u_prime;
                U_y_new=u_y_new+mean(U1);
                %figure(6)
                %plot(tshift,U_y,'b*')
                %hold on
                %plot(tshift,U_y_new,'r*')
            end
            if i==3
                u_z=u1;
                U_z=U1;
                u_z_new=u_prime;
                U_z_new=u_z_new+mean(U1);
                %figure(6)
                %plot(tshift,U_z,'b*')
                %hold on
                %plot(tshift,U_z_new,'r*')
            end
            %ckey=input('Press any key to continue ','s');
            close all

        end


        %%% plot original and despiked time series

        figure;
        ax(1) = subplot(3,1,1);
        plot(t/fs,U_x);hold on;
        plot(t/fs,U_x_new);
        xlabel('time (s)')
        ylabel('X velocity (m/s)')
        ax(2) = subplot(3,1,2);
        plot(t/fs,C_x);hold on;
        xlabel('time (s)')
        ylabel('X Correlation')
        ax(3) = subplot(3,1,3);
        plot(t/fs,S_x);hold on;
        xlabel('time (s)')
        ylabel('X SNR')
        linkaxes(ax,'x');

        print(strcat(filenames(k).name(1:length(filenames(k).name)),'_X'),'-dpng');
        saveas(ax,strcat(filenames(k).name,'_X.fig'));


        %%% replace Corr and SNR by nan when U was despiked
        C_x_new(find(round(abs((U_x_new-U_x)),4)>round(min(abs(U_x_new-U_x)),4))) = nan;
        S_x_new(find(round(abs((U_x_new-U_x)),4)>round(min(abs(U_x_new-U_x)),4))) = nan;


        figure;
        ax(1) = subplot(3,1,1);
        plot(t/fs,U_y);hold on;
        plot(t/fs,U_y_new);
        xlabel('time (s)')
        ylabel('Y velocity (m/s)')
        ax(2) = subplot(3,1,2);
        plot(t/fs,C_y);hold on;
        xlabel('time (s)')
        ylabel('Y Correlation')
        ax(3) = subplot(3,1,3);
        plot(t/fs,S_y);hold on;
        xlabel('time (s)')
        ylabel('Y SNR')
        linkaxes(ax,'x');

        print(strcat(filenames(k).name(1:length(filenames(k).name)),'_Y'),'-dpng');
        saveas(ax,strcat(filenames(k).name,'_Y.fig'));

        %%% replace Corr and SNR by nan when U was despiked
        C_y_new(find(round(abs((U_y_new-U_y)),4)>round(min(abs(U_y_new-U_y)),4))) = nan;
        S_y_new(find(round(abs((U_y_new-U_y)),4)>round(min(abs(U_y_new-U_y)),4))) = nan;


        figure;
        ax(1) = subplot(3,1,1);
        plot(t/fs,U_z);hold on;
        plot(t/fs,U_z_new);
        xlabel('time (s)')
        ylabel('Z velocity (m/s)')
        ax(2) = subplot(3,1,2);
        plot(t/fs,C_z);hold on;
        xlabel('time (s)')
        ylabel('Z Correlation')
        ax(3) = subplot(3,1,3);
        plot(t/fs,S_z);hold on;
        xlabel('time (s)')
        ylabel('Z SNR')
        linkaxes(ax,'x');

        print(strcat(filenames(k).name(1:length(filenames(k).name)),'_Z'),'-dpng');
        saveas(ax,strcat(filenames(k).name,'_Z.fig'));

        %%% replace Corr and SNR by nan when U was despiked
        C_z_new(find(round(abs((U_z_new-U_z)),4)>round(min(abs(U_z_new-U_z)),4))) = nan;
        S_z_new(find(round(abs((U_z_new-U_z)),4)>round(min(abs(U_z_new-U_z)),4))) = nan;



        data_new=data;
        data_new(tb:te,3)=U_x_new;
        data_new(tb:te,4)=U_y_new;
        data_new(tb:te,5)=U_z_new;
        data_new(tb:te,12)=C_x_new;
        data_new(tb:te,13)=C_y_new;
        data_new(tb:te,14)=C_z_new;
        data_new(tb:te,9)=S_x_new;
        data_new(tb:te,10)=S_y_new;
        data_new(tb:te,11)=S_z_new;


        % sprintf(strcat(filenames(k).name,'_despike.dat'),data_new);
        % fprintf(strcat(filenames(k).name,'_despike.dat'),data_new);
        writematrix(data_new,strcat(filenames(k).name,'_despike.dat'),'Delimiter','\t');

        close all;
        clearvars -except filenames acths acfas
    end

