%% Peak Fitting Tool
% with a selection of different peak shapes and optional symmetrization of exponentionally-broadened peaks. (Requires peakfit.m in the path). To see the graphs on the right, right-click on the right panel and select "Disable synchronous scrolling". Tom O'Haver 5/30/2023

 file= uigetfile('*.csv;*.xlsx');% Click this button to load data from 
mydata=xlsread(file); disp(file) %            disk in xlsx or csv format. 

%

% Hint: right-click on the empty space on the right and select "Disable synchronous scrolling"
startpc=10; % Percentage of data points to start data selection
endpc=57; % Percentage of data points to end data selection

PreProcess=true ; % Optional data processing before curve fitting
SymmetrizeFactor=2.87; % "De-tailing" for skewed peaks (Double-click to change range)
SmoothWidth=14; % Smooth only if using symmetrizatiion
NumPasses=1; % Number of sliding average passes (1-5)

% Controls for least-squares peak fitting
FitPeaks=true; % Perform curve fit. De-select while making fitting selections.
PeakShape="Gaussian" ;
NumPeaks=4; % Number of peaks in fitting model
NumTrials=1; % Takes best of "NumTrials" curve fit trials
extra=100; % Shape parameter for variable-shape peaks (EMG, G/L blend, etc)
SetStart=true; % Opionally set estimated peak positions, expressed as percentage of the total x-axis range.
Startx(1)=34.1; % Peak 1
Startx(2)=56; % Peak 2
Startx(3)=69; % Peak 3
Startx(4)=55.5; % Peak 4
Startx(5)=63.9; % Peak 5
Startx(6)=70.5; % Peak 6
Startx(7)=75.1; % Peak 7
Startx(8)=27.9; % Peak 8
BaselineSelection="No Correction";
BaselineShift=0; % Percent vertical baseline shift (+ or -)
bipolar=false; % Show both positive and negative on y axis
format short g
format compact
NumPoints=length(mydata);
startpoint=round(startpc*NumPoints./100);
endpoint=round(endpc*NumPoints./100);
x=mydata(startpoint:endpoint,1); % Set this integer to the column number of the x data
y=mydata(startpoint:endpoint,2)+0.01.*BaselineShift.*max(mydata(:,2)); % Set this integer to the column number of the y data

if PreProcess==true
    % Symmetrize by weighted first-derivative addition
    ysym=y+sqrt((NumPoints./100).^2.*SymmetrizeFactor).*deriv(y);

    % Recursive sliding average smoothing
    y=fastsmooth(ysym,SmoothWidth,NumPasses,1);
end

if FitPeaks==true
    % Calculate first guess vector 
    % FirstGuess=calcstart(x,NumPeaks,0,extra);

    % Fit peaks 
    switch PeakShape
        case 'Gaussian'
            ShapeNumber=1 ;
        case 'Lorentzian'
            ShapeNumber=2 ;
        case 'logistic distribution'
            ShapeNumber=3 ;
        case 'Pearson'
            ShapeNumber=4 ;
        case 'exponentially broadened Gaussian'
            ShapeNumber=5 ;
        case 'equal-width Gaussians'
            ShapeNumber=6 ;
        case 'equal-width Lorentzians'
            ShapeNumber=7 ;
        case 'exponentially broadened equal-width Gaussians'
            ShapeNumber=8 ;
        case 'exponential pulse'
            ShapeNumber=9 ;
        case 'Gaussian/Lorentzian blend'
            ShapeNumber=13 ;
    end
  figure(1)
  widthguess=(max(x)-min(x))/(4*NumPeaks);
  deltax=x(3)-x(2);
  xrange=max(x)-min(x);
  FirstGuess=[];
  for k=1:NumPeaks
     FirstGuess=[FirstGuess min(x)+xrange*Startx(k)/100 widthguess];
  end

  switch BaselineSelection
      case 'No Correction'
          BaselineMode=0;
      case 'Tilted mode'
          BaselineMode=1;
      case 'Quadratic mode'
          BaselineMode=2;
       case 'Flat mode'
          BaselineMode=3;
  end
%   
if SetStart==true
    [Pfit,GOF]=peakfit([x,y],0,0,NumPeaks,ShapeNumber,extra,NumTrials,FirstGuess,BaselineMode,0,1,bipolar);
else
    [Pfit,GOF]=peakfit([x,y],0,0,NumPeaks,ShapeNumber,extra,NumTrials,0,BaselineMode,0,1,bipolar);
end
% NumPeaks=length(Pfit);

if FitPeaks==true
    disp(['Peak shape = '+PeakShape])
    disp(['Fitting error=' num2str(GOF(1)) '%    R2= ' num2str(GOF(2))])
    if ShapeNumber==5||ShapeNumber==8||ShapeNumber==13
        disp(['Shape parameter = ' num2str(extra)])
    end
    disp('peak #  Position Height  Width    Area')
    for n=1:NumPeaks
        disp(['    ' sprintf('%0.4g',n) '    ' sprintf('%0.4g',Pfit(n,2)) '   '  sprintf('%0.4g',Pfit(n,3))  '   '  sprintf('%0.4g',Pfit(n,4)) '    '  sprintf('%0.4g',Pfit(n,5))]);
    end
end
else
    clf
    plot(x,y)
    xlabel('x')
    ylabel('y')
    grid
    title(file)
    if SetStart==true
        % Mark starting peak positions with vertical dashed lines
        % Determine locations for peak (vertical line) markers
        xrange=max(x)-min(x);
        hold on
        for marker=1:NumPeaks
            markx=min(x)+xrange*Startx(marker)/100;
            plot([markx markx],[min(y) max(y)],'m--')
        end % for marker
        hold off
    end
end

%

function SmoothY=fastsmooth(Y,w,type,ends)
% fastsmooth(Y,w,type,ends) smooths vector Y with smooth
%  of width w. Version 3.0, October 2016.
% The argument "type" determines the smooth type:
%   If type=1, rectangular (sliding-average or boxcar)
%   If type=2, triangular (2 passes of sliding-average)
%   If type=3, pseudo-Gaussian (3 passes of sliding-average)
%   If type=4, pseudo-Gaussian (4 passes of same sliding-average)
%   If type=5, multiple-width (4 passes of different sliding-average)
% The argument "ends" controls how the "ends" of the signal
% (the first w/2 points and the last w/2 points) are handled.
%   If ends=0, the ends are zero.  (In this mode the elapsed
%     time is independent of the smooth width). The fastest.
%   If ends=1, the ends are smoothed with progressively
%     smaller smooths the closer to the end. (In this mode the
%     elapsed time increases with increasing smooth widths).
% fastsmooth(Y,w,type) smooths with ends=0.
% fastsmooth(Y,w) smooths with type=1 and ends=0.
%
% Examples:
% fastsmooth([1 1 1 10 10 10 1 1 1 1],3)= [0 1 4 7 10 7 4 1 1 0]
% fastsmooth([1 1 1 10 10 10 1 1 1 1],3,1,1)= [1 1 4 7 10 7 4 1 1 1]
%
% x=1:100;
% y=randn(size(x));
% plot(x,y,x,fastsmooth(y,5,3,1),'r')
% xlabel('Blue: white noise.    Red: smoothed white noise.')
%
% Demonstration scripts and functions: SmoothExperiment.m,
% SmoothWidthTest.m, smoothdemo.m, SmoothOptimization.m,
% DemoSegmentedSmooth.m, DeltaTest.m, SmoothVsCurvefit.m
%
% Related functions: SegmentedSmooth.m, medianfilter.m, killspikes.m
% Download from
% https://terpconnect.umd.edu/~toh/spectrum/functions.html

% Copyright (c) 2012,2018 Thomas C. O'Haver
%
% Permission is hereby granted, free of charge, to any person obtaining a copy
% of this software and associated documentation files (the "Software"), to deal
% in the Software without restriction, including without limitation the rights
% to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
% copies of the Software, and to permit persons to whom the Software is
% furnished to do so, subject to the following conditions:
%
% The above copyright notice and this permission notice shall be included in
% all copies or substantial portions of the Software.
%
% THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
% IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
% FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
% AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
% LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
% OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
% THE SOFTWARE.
if nargin==2, ends=0; type=1; end
if nargin==3, ends=0; end
switch type
    case 1
        SmoothY=sa(Y,w,ends);
    case 2
        SmoothY=sa(sa(Y,w,ends),w,ends);
    case 3
        SmoothY=sa(sa(sa(Y,w,ends),w,ends),w,ends);
    case 4
        SmoothY=sa(sa(sa(sa(Y,w,ends),w,ends),w,ends),w,ends);
    case 5
        SmoothY=sa(sa(sa(sa(Y,round(1.6*w),ends),round(1.4*w),ends),round(1.2*w),ends),w,ends);
end
end

function SmoothY=sa(Y,smoothwidth,ends)
w=round(smoothwidth);
SumPoints=sum(Y(1:w));
s=zeros(size(Y));
halfw=round(w/2);
L=length(Y);
for k=1:L-w
    s(k+halfw-1)=SumPoints;
    SumPoints=SumPoints-Y(k);
    SumPoints=SumPoints+Y(k+w);
end
s(k+halfw)=sum(Y(L-w+1:L));
SmoothY=s./w;
% Taper the ends of the signal if ends=1.
if ends==1
    startpoint=(smoothwidth + 1)/2;
    SmoothY(1)=(Y(1)+Y(2))./2;
    for k=2:startpoint
        SmoothY(k)=mean(Y(1:(2*k-1)));
        SmoothY(L-k+1)=mean(Y(L-2*k+2:L));
    end
    SmoothY(L)=(Y(L)+Y(L-1))./2;
end
end

% function FirstGuess=ClickStart(x,sy,NumPeaks)
% %              of each proposed component peak on the pop-up graphic.)           
% [clickX,~] = ginput(NumPeaks);
% % Create a "start" vector using these peak positions, with peak
% % widths
% n=length(x);
% width=n/(5*NumPeaks);
% FirstGuess=[];
% for k=1:NumPeaks
%     FirstGuess=[FirstGuess clickX(k) width]
% end
% end

function d=derivxy(x,y)
% First derivative of y with respect to x using 2-point central difference.
%  T. C. O'Haver, 2011. Corrected 2/4/14
% Example:
%  x = [1 2 4 7 10 14 20 30];y = 2*x;plot(x,y,'o-');dy=derivxy(x,y)
% ans =
%      2     2     2     2     2     2     2     2
% Compare to:
% x = [1 2 4 7 10 14 20 30];y = 2*x;deriv(y)
% ans =
%      2     3     5     6     7    10    16    20
%
n=length(y);
d=zeros(size(y));
d(1)=(y(2)-y(1))./(x(2)-x(1));
d(n)=(y(n)-y(n-1))./(x(n)-x(n-1));
for j = 2:n-1
  d(j)=(y(j+1)-y(j-1)) ./ ((x(j+1)-x(j-1)));
end
end