clear % See https://terpconnect.umd.edu/~toh/spectrum/SignalsAndNoise.html#DetectionLimit
x=1:1000; % Max value is the number of data points in whole signal
signal=3  ; % Magnitude of the signal peak (change as desired)
noise=1; % Standard deviation of the constant random white noise
TargetSNR=3 ; % Your favorite definition of SNR at the LOD (usually 2 or 3)
PeakWidth=300; % Peak width in data points (change as desired)
AveragePoints=1; % Increase this number to average points and improve SNR
Baseline = .1; % Sets the minimum baseline noise.

% Calculations
lx=length(x);
y=signal.*rectanglepulse(x,lx/2,(PeakWidth))+Baseline; 
noisearray=y.*noise.*randn(size(x)); % Proportional (heteroscedastic) noise
maxnoise=max(noisearray);
SNR=signal/std(noisearray);
oy=y+noisearray;
if AveragePoints>1 % Smooth the signal if SmoothWidth is greater than 1
   oy=fastsmooth(oy,AveragePoints,1); 
   noisearray=fastsmooth(noisearray,AveragePoints,1);
   maxnoise=max(noisearray);
end
TopWidth=round(PeakWidth/2-AveragePoints/2);
SignalMark=mean(oy(lx/2-TopWidth:lx/2+TopWidth));
figure(1)
clf
plot(x,oy,[min(x) max(x)],[max(oy) max(oy)],'k',[min(x) max(x)],[min(oy) min(oy)],'k',[lx/2-TopWidth lx/2+TopWidth],[SignalMark SignalMark],'r','linewidth',2)
grid
ylabel('Observed signal')
title('Signal-to-noise ratio (SNR) of peak height - proportional noise')
SignalDetected=0;
for trial=1:100
    noisearray=noise.*randn(size(x));
    maxnoise=max(noisearray);
    SNR=signal/std(noisearray);
    oy=y+noisearray;
    if AveragePoints>1 % Smooth the signal if SmoothWidth is greater than 1
        oy=fastsmooth(oy,AveragePoints,1);
        noisearray=fastsmooth(noisearray,AveragePoints,1);
        maxnoise=max(noisearray);
    end
    SNR=signal/std(noisearray);
    oy=y+noisearray;   
    svy(trial)=oy(round(lx/2)); % Single value y
    ObservedBaseline=mean(oy([round(1:lx/20) round(lx-lx/20:lx)]));
    ObservedSignal(trial)=mean(oy(lx/2-TopWidth:lx/2+TopWidth))-Baseline;
    ObservedNoise=std(noisearray([round(1:lx/2-TopWidth) (round(lx-lx/2-TopWidth):lx)]));
    ObservedSNR=ObservedSignal(trial)./ObservedNoise;
    if ObservedSNR>TargetSNR,SignalDetected=SignalDetected+1;end
end
xlabel(['Target SNR = ' num2str(TargetSNR)  '     SNR of peak = ' num2str(ObservedSNR,2) '     RSD of mean height = ' num2str(prsd(ObservedSignal),2) '%    Points averaged = ' num2str(AveragePoints)])
disp(['Signal detected in ' num2str(SignalDetected) '% of the individual data points.' ])
disp(['Average of averaged signals: ' num2str(mean(ObservedSignal)) ])
disp(['Relative standard deviation of averaged signals: ' num2str(prsd(ObservedSignal)) '%' ])
disp(['Average of single point signals: ' num2str(mean(svy)) ])
disp(['Relative standard deviation of single point signals: ' num2str(prsd(svy)) '%' ])

figure(2);
BinSize=30;
histogram(ObservedSignal,BinSize)
title('Statistical distribution of the measured signals')
xlabel(['bin size = '  num2str(BinSize)])
figure(1)
 
% Functions called by this script
function g = rectanglepulse(x,pos,wid)
%rectangle function.  pos=position; wid=half-width (both scalar)
%rectangle(x,pos,wid), where x may be scalar or vector,
%pos=position; wid=half-width (both scalar)
% T. C. O'Haver, 2016
% Example
% x=[0:.1:10];plot(x,rectanglepulse(x,5.5,2.3),'.')
g=zeros(size(x));
hw=wid./2;
for i=1:length(x)
if x(i)<pos-hw,g(i)=0;end
if x(i)>pos-hw,g(i)=1;end
if x(i)>pos+hw,g(i)=0;end
end
end

function prelstddev=prsd(x)
% Percent relative standard deviation of vector x
prelstddev=100.*std(x)./mean(x);
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