% Series of events

% Before analysis, make sure that your series is contained in these
% variables 'int' and 'time':
% int=interval since last event (e.g., nanosecond)
% time = time of the event (e.g., second)

d=max(size(int)); % length of series
event=1:d;   % create array of event numbers

% Cumulative plot of the number of events against time
plot(time,event);

% Try linear fitting the curve (on Figure toolbar, Tools/Basic fitting)
% and then plot residuals.


%%
% Plot the number of events in each successive time period
nperiods=50;
hist(time,nperiods);

%%
% Plot return map
plot(int(1:d-1),int(2:d),'o')

%%
% Testing for randomness -- Poisson distribution
n=hist(time,nperiods);  % n contains the number of events in each successive time interval 
nbins=20;
[Observed nout1]=hist(n,nbins);   % Observed = number of intervals with n counts
                           % nout1 = positions of histigram bins
                           
dx=floor(min(nout1(2:nbins)-nout1(1:nbins-1))); % integer interval in histogram
dx=max(dx,1);
nout2=nout1;
for i=1:nbins
nout2(i)=floor(nout1(1))+dx*(i-1);      % define new (integer) positions of bins
end
[Observed nout]=hist(n,nout2);        % new positions of histogram bins are now in nout
hist(n,nbins)
%%
% If intervals are random then n is Poisson-distributed. 
% Perform chi-square test:

T=time(d)/nperiods;   % length of sampling period
mu = d/nperiods;             % expected mean of Poisson distribution (# of counts per period)
Expected=nperiods*dx*poisspdf(nout,mu);  % Expected number of intervals with n counts

chi2=sum((Observed-Expected).^2./Expected)
df=max(size(Observed))-2

