clear all
close all force
 disp('Permutation Test for Trend')
  lw = 2; 
  set(0, 'DefaultAxesFontSize', 17);
  fs = 17;
  msize = 10;
  

rand('seed',1)
 

% Suppose that we are monitoring a production process for
% 11 hours and  every hour record  temperatures in deg F,



% X_1, X_2, \dots, X_11.
% Significant upward or downward trends could be critical
% for the process.

% We are interested in testing H_0: Xi's are independent and identically
% distributed (no trend)
% versus H_1: there is an overall increasing trend

 X=[176 175 164 175 168  160 179 181 207 189 205];
%X=[22 14 14 16 24 13 18 15 17 15 12 20];
n=length(X)
i=1:n;
      figure(1); plot(i,X,'o' ,'MarkerSize',msize,...
                                          'MarkerEdgeColor','k',...
                                           'MarkerFaceColor','b')
xlabel('Hours')
ylabel('Temperature')                                     
%print -depsc 'C:\STAT\Boot\Booteps\permute1.eps'
          
f = i * X'   % 12227
Ef = n*mean(i) * mean(X)   %11874
Ef =  (n+1)/2  * sum(X)  %11874
Ef = n  *  (n+1)/2 * mean(X)
s2f = (n-1) * var(i) * var(X)  %2.5332e+04
s2f =   (n-1)*n*(n+1)/12  * var(X)  %2.5332e+04

Z=(f - Ef)/sqrt(s2f) %2.2179
1-normcdf(Z) %0.0133
 
 % 
fps =[];
count=0;
B=250000;
for b=1:B
    Xp=X(randperm(n));
    fp = i * Xp';
    count = count + (fp >= f);
    fps=[fps fp];
end
count
count/B  %0.0078
figure(2)
  histn(fps, 11350, 15,12425);
  hold on
  plot([f f],[0, 0.003],'r-','LineWidth',lw)
  plot([Ef Ef],[0, 0.003],'g-','LineWidth',lw)
  legend('hist of fps','observed flux','expected flux','Location','northwest')
  xlabel('$\sum  i  X_i$', 'Interpreter','LaTeX')
 
  %print -depsc 'C:\STAT\Boot\Booteps\permute2.eps'
          

  
  