 
clear all
close all
 disp('Binary Response: Bumpus Sparrow')

%-----------------figure defaults
lw = 2.5;  
set(0, 'DefaultAxesFontSize', 16);
fs = 15;
msize = 8;
randn('seed',3)



load 'C:\BESTAT\Logistic\Logisticdat\bumpus.mat'
 mind = bumpus.sex >= 11 %male sparrows
 Y = bumpus.surv(mind);
 Xlbt = bumpus.lbt(mind);
 Xae = bumpus.ae(mind);
 Xwei = bumpus.wei(mind);
  Xlbh = bumpus.lbh(mind);
 Xhum = bumpus.hum(mind);
 Xfem = bumpus.fem(mind);
  Xtib = bumpus.tib(mind);
 Xwos = bumpus.wos(mind);
 Xkos = bumpus.kos(mind);

 
 
X =[Xlbt  Xae Xwei  Xlbh Xhum  Xfem Xtib Xwos Xkos];

Xdes =[ones(size(Y)) X];  %with the intercept: n x p
 [n p] = size(Xdes); 
 alpha = 0.05;  %alpha for CIs

[b, dev, stats]=glmfit(X,Y, 'binomial','link','logit')
 lin = Xdes * b  %linear predictor, n x 1 vector

figure(1)
plot(lin, Y,'o','MarkerSize',msize,...
          'MarkerEdgeColor','k','MarkerFaceColor','g')          
 xx = -6:0.01:4;
 mp =  exp(xx)./(1 + exp(xx));
 hold on
 plot(xx, mp,'r-','LineWidth',lw)
 axis([-6 4 0 1])
 xlabel('Score','Interpreter','LaTeX')
 ylabel('Probability of Survival','Interpreter','LaTeX') 
 legend('Observations','Logistic Fit',2)
 %print -depsc 'C:\Springer\Logistic\Logisticeps\arrh1.eps'
%Xlbt  Xae Xwei  Xlbh Xhum  Xfem Xtib Xwos Xko
%    26.2380
%    -0.7488 lbt
%     0.0928 ae
%    -0.8576 wei
%     0.5247 lbh
%    34.3716 hum
%    23.8114 fem
%    -1.8177 tib
%    28.1994 wos
%    23.4389 kos
phat = exp(lin)./(1 + exp(lin));
  V = diag( phat .* (1 - phat) ); 
  sqrtV = diag( sqrt(phat .* (1 - phat) ))
  sb = sqrt(   diag( inv( Xdes' * V * Xdes ) ) )
  % inv( Xdes' * V * Xdes ) is stats.covb
  % Wald tests for parameters beta
  z = b./sb  %tests for beta_i = 0, i=0,...,p-1
  pvals = 2 * normcdf(-abs(z))   %p-values 
  
  figure(2)
  range = [2:10];
  errorbar(range-1, b(range), 1.96*sb(range),'o','MarkerSize',msize,...
       'LineWidth',2,   'MarkerEdgeColor','k','MarkerFaceColor','g')  
  hold on
  plot([-1:10],0*[-1:10],'r-')
  xlabel('Index','Interpreter','LaTeX');  ylabel('$b \pm 1.96 s_b$','Interpreter','LaTeX')
  axis([0.5 10.5 -50.4 100.3])
  hold off
  
  figure(3)
  range = [2:5];
  errorbar(range-1, b(range), 1.96*sb(range),'o','MarkerSize',msize,...
       'LineWidth',2,   'MarkerEdgeColor','k','MarkerFaceColor','g')  
  hold on
  plot([-1:6],0*[-1:6],'r-')
  xlabel('Index','Interpreter','LaTeX'); ylabel('$b \pm 1.96 s_b$','Interpreter','LaTeX')
   axis([-0.5 5.5 -2 2])
  hold off
  %print -depsc 'C:\Springer\Logistic\Logisticeps\arrhrb.eps'
   
%  %(1-alpha)*100% CI for betas
   CIs = [b - norminv(1 - alpha/2) * sb , b + norminv(1-alpha/2) * sb]
   %(1-alpha)*100% CIs for odds ratios
   CIsOR = exp([b-norminv(1-alpha/2)*sb , b+norminv(1-alpha/2)*sb])
