%GLMLAB   Generalized linear models in MATLAB.
%USE:     glmlab 
%         glmlab  allows the user to alter the  response variable (y),
%          the covariates (x variables), the offset variable and the
%          prior weights variable, plus set numerous options.
%         Enter the names of the variables in the appropriate window.
%          (The variable must be defined in the  MATLAB  workspace.)

%Copyright 1996--1999 Peter Dunn
%08 March 1999

%GLMLAB_INFO_{i} contains the following for 1 <= i <= 25:
%  1  Error distribution function (eg 'normal')
%  2  Link function (eg 'log');
%  3  Scale parameter (eg 'md' or 3.2)
%  4  Residual Type (eg 'deviance')
%  5  1 to recycle fitted values, 0 elsewise
%  6  1 to include  a constant in the fitting, 0 elsewise
%  7  The output format, a 3x1 vector
%  8  The name of the file recording the details of the session
%  9  The name of the y variable
% 10  The names of the X variables
% 11  The name of the prior weights variable
% 12  The name of the offset variable
% 13  The names of the X variables, one per row
% 14  The y variable
% 15  The X variables
% 16  The prior weights variable
% 17  The offset variable
% 18  The residuals
% 19  The fitted values
% 20  The deviance
% 21  The residual degrees of freedom
% 22, 23, 24  Flags for when its OK to do certain things.
% 25  The status of warning messages.

watchon;

%See if glmlab already running.
set(0,'ShowHiddenHandles','on');
GLW_ = findobj('Tag','glmlab_main');

if ~isempty( GLW_),                           %if glmlab is found...

   HE_=errordlg('glmlab  is already running.',...
                'Cannot start glmlab!');     %...don't start a new one....
   set(HE_,'WindowStyle','modal');
   figure(GLW_);                             %make it current figure
   clear HE_ GLW_
   watchoff;
   return;                                   %...and return.

end;

clear GLW_

set(0,'ShowHiddenHandles','off');

%Set up defaults
GLMLAB_INFO_=cell(25,1);
GLMLAB_INFO_{1}='normal';
GLMLAB_INFO_{2}='id';
GLMLAB_INFO_{3}='md';
GLMLAB_INFO_{4}='pearson';
GLMLAB_INFO_{5}=0;
GLMLAB_INFO_{6}=1;
GLMLAB_INFO_{7}=[0 1 1];
GLMLAB_INFO_{22}=1;
GLMLAB_INFO_{23}=0;
GLMLAB_INFO_{24}=0;
GLMLAB_INFO_{25}='backtrace';

figure('Name','glmlab Main Window',...       %new figure
 'tag','glmlab_main','MenuBar','none',...
 'Resize','off','Pointer','watch',...
 'Visible','off',...
 'CloseRequestFcn','menuwork(50);');
   
axis off;                                    %no axes
glmsplsh;                                    %splash screen
%Load some details that are needed

figure( findobj('tag','glmlab_main'));        %make gl window current window

L1=dllist(which('llist'),'l');               %load link functions
D1=dllist(which('dlist'),'d');               %load distributions

%MENU ALONG THE TOP
%FILE
%LOADDIR=strrep(which('dummydta'),'dummydta.m','*.mat'); %default
uimenu(findobj(gcf,'tag','glmlab_main'),...  %File menu
 'Label','File ','tag','filem')
 uimenu(findobj(gcf,'tag','filem'),...           %LOAD data file info
  'Label','LOAD Data File',...
  'Accelerator','L',...
  'Callback','menuwork(23); watchoff;' );

%  'Callback', ['LOADDIR=strrep(which(''dummydta''),''dummydta.m'',''*.mat''); ',... %default
%               '[AA,BB]=uigetfile(''',LOADDIR,''',''Load Data'');',...
%               'eval(''load([BB,AA]);ERR_FLAG=0;'',''ERR_FLAG=1;'');',...
%               'if ERR_FLAG, opterr(6,AA); else opterr(7,AA); end; clear ERR_FLAG AA BB LOADDIR']);
% clear LOADDIR

 uimenu(findobj(gcf,'tag','filem'),...           %load model
  'Label','Save glmlab Model',...
  'Callback','menuwork(21);watchoff;',...
  'Separator','on');
 uimenu(findobj(gcf,'tag','filem'),...           %save model
  'Label','Load glmlab Model',...
  'Callback','menuwork(22);watchoff;');
 uimenu(findobj(gcf,'tag','filem'),...           %quit
  'Label','QUIT glmlab and Lose Settings',...
  'Accelerator','Q',...
  'Callback','menuwork(50);',...
  'Separator','on');
 uimenu(findobj(gcf,'tag','filem'),...           %exit matlab
  'Label','EXIT MATLAB',...
  'Accelerator','X',...
  'Callback','menuwork(65);');


%DISTRIBUTION
CALLBACK=[];
uimenu(findobj(gcf,'tag','glmlab_main'),...      %distribution menu
 'Label','Distribution ','tag','distm');
for III=1:length(D1),                        %for each distribution given...
   CALLBACK=str2mat(CALLBACK,['''menuwork(1,''''',D1{III},''''');''']);
   uimenu(findobj(gcf,'tag','distm'),'Label',D1{III},...
    'tag',D1{III},...                        %set callback, tag and label
    'Callback',eval(CALLBACK(III+1,:)));
   if III==6,                                %Separate supplied from user
      set(findobj(gcf,'tag',D1{III}),'Separator','on');
   end;
end;

set(findobj(gcf,'tag','normal'),'Checked','on'); %Indicate normal as default

%LINK
CALLBACK=[];
uimenu(findobj(gcf,'tag','glmlab_main'),...      %link menu
 'Label','Link ','tag','linkm');
for II=1:length(L1),                         %for each link given
   CALLBACK=str2mat(CALLBACK,['''menuwork(2,''''',L1{II},''''');''']);
   uimenu(findobj(gcf,'tag','linkm'),'Label',L1{II},...
    'tag',L1{II},...                         %set callback, tag and label
    'Callback',eval(CALLBACK(II+1,:)));
   if ~strcmp(GLMLAB_INFO_{1},'binoml'),     %Disable binomial link functions
      if strcmp(L1{II},'logit')|...
         strcmp(L1{II},'complog')|...
         strcmp(L1{II},'probit'),
            set(findobj(gcf,'tag',L1{II}),'Enable','off');
      end;
   end;
   %Now indicate selected distribution
   if II==9,                                 %Separate supplied from user
      set(findobj(gcf,'tag',L1{II}),'Separator','on');
   end;
end;

set(findobj(gcf,'tag','id'),'Checked','on');     %Indicate id as default
clear CALLBACK III II D1 L1

%SCALEPAR
uimenu(findobj(gcf,'tag','glmlab_main'),...      %scale parameter menu
 'Label','Scale Parameter ',...
 'tag','scalem');
uimenu(findobj(gcf,'tag','scalem'),...           %mean deviance: default
 'Label','Mean Deviance',...
 'Checked','on',...
 'tag','md','Callback','menuwork(4,1);');
uimenu(findobj(gcf,'tag','scalem'),...           %fixed value
 'tag','val',...
 'Label','Fixed Value: 1',...
 'Callback','menuwork(4,2);');

%RESIDUAL TYPE
uimenu(findobj(gcf,'tag','glmlab_main'),...      %residual menu
 'Label','Residual Type ',...
 'tag','residm');
uimenu(findobj(gcf,'tag','residm'),...           %pearson: default
 'Label','Pearson',...
 'Checked','on',...
 'tag','pearson',...
 'Callback','menuwork(3,1);');
uimenu(findobj(gcf,'tag','residm'),...           %deviance
 'Label','Deviance',...
 'tag','deviance',...
 'Callback','menuwork(3,2);');
uimenu(findobj(gcf,'tag','residm'),...           %quantile
 'Label','Quantile',...                      % since default distn is normal,
 'Enable','on',...                           % should be OK to be enabled
 'tag','quantile',...
 'Callback','menuwork(3,3);');


%OPTIONS
uimenu(findobj(gcf,'tag','glmlab_main'),...      %options menu
 'Label','Options ',...
 'tag','optm');
uimenu(findobj(gcf,'tag','optm'),...             %new model
 'Label','Declare New Model',...
 'Accelerator','N',...
 'Callback','menuwork(8);');
uimenu(findobj(gcf,'tag','optm'),...              %restore defaults
 'Label','Restore Default Settings',...
 'Accelerator','D',...
 'Callback','menuwork(7);');
uimenu(findobj(gcf,'tag','optm'),...               %warning status
 'Label','MATLAB Warning Message Status',...
 'tag','warn_st');
  uimenu(findobj(gcf,'tag','warn_st'),...          %...backtrace
   'Label','backtrace',...
   'Callback','menuwork(75,''backtrace'');',...
   'tag','ws_backtrace',...
   'Checked','on');
  uimenu(findobj(gcf,'tag','warn_st'),...          %...on
   'Label','on',...
   'Callback','menuwork(75,''on'');',...
   'tag','ws_on');
  uimenu(findobj(gcf,'tag','warn_st'),...         %...off
   'Label','off',...
   'Callback','menuwork(75,''off'');',...
   'tag','ws_off');
uimenu(findobj(gcf,'tag','optm'),...              %fitting parameters
 'Label','Change Fitting Parameters',...
 'tag','dfit_par',...
 'Callback','menuwork(80);');
uimenu(findobj(gcf,'tag','optm'),...              %include constant
 'Label','Include a Constant/Intercept Term in Model',...
 'Accelerator','C',...
 'Checked','on',...
 'tag','constant',...
 'Callback','menuwork(70);',...
 'Separator','on');
uimenu(findobj(gcf,'tag','optm'),...              %output display
 'tag','outputm',...
 'Label','Output Display');
  uimenu(findobj(gcf,'tag','outputm'),...         %...model info
   'Label','Display Model Information',...
   'Accelerator','F',...
   'tag','fitinf',...
   'Callback','menuwork(40,1);');
  uimenu(findobj(gcf,'tag','outputm'),...         %...parameter values
   'Label','Display Parameter Values',...
   'Accelerator','P',...
   'tag','pvals',...
   'Checked','on',...
   'Callback','menuwork(40,2);');
  uimenu(findobj(gcf,'tag','outputm'),...         %...display vars used
   'Label','Display Variables Used',...
   'Accelerator','V',...
   'tag','varinf',...
   'Checked','on',...
   'Callback','menuwork(40,3);');
uimenu(findobj(gcf,'tag','optm'),...              %recycle fitted values
 'Label','Recycle Fitted Values',...
 'Accelerator','R',...
 'tag','recycle',...
 'Callback','menuwork(40,4);');

%RESIDUAL PLOTS
uimenu(findobj(gcf,'tag','glmlab_main'),...       %plots menu
 'Label','Plots ',...
 'tag','rplots',...
 'Enable','off');
  uimenu(findobj(gcf,'tag','rplots'),...          %res vs response
   'Label','Residuals vs Response (y)',...
   'tag','resvy',...
   'Callback','plotwork(1);')
  uimenu(findobj(gcf,'tag','rplots'),...          %res vs covars
   'Label','Residuals vs Covariates (X)',...
   'tag','resvc',...
   'Callback','pickcvs;plotwork(2);');
  uimenu(findobj(gcf,'tag','rplots'),...          %normal prob plot
   'Label','Normal Probability Plot of Residuals',...
   'tag','npplot',...
   'Callback','plotwork(3);')
  uimenu(findobj(gcf,'tag','rplots'),...          %res vs fitted
   'Label','Residual vs Fitted Values',...
   'tag','resvf',...
   'Callback','plotwork(4);');
  uimenu(findobj(gcf,'tag','rplots'),...          %res vs transformed
   'Label','Residuals vs Transformed Fitted Values',...
   'tag','resvxf',...
   'Callback','plotwork(5);',...
   'Enable','off')                                 %no transform for normal(the default)
  uimenu(findobj(gcf,'tag','rplots'),...          %fitted vs quant equiv
   'Label','Fitted Values vs Quantile Equivalents',...
   'tag','qequiv',...
   'Callback','plotwork(6);');

%HELP
uimenu(findobj(gcf,'tag','glmlab_main'),...       %help menu
 'Label','Help ',...
 'tag','helpm');
  uimenu(findobj(gcf,'tag','helpm'),...           %on-line manual
   'Label','On-line Manual',...
   'Callback','web(''http://www.sci.usq.edu.au/staff/dunn/glhtml/html/gli.html'');')
  uimenu(findobj(gcf,'tag','helpm'),...           %main window items
   'Label','Help with MAIN WINDOW Items',...
   'Callback','helpvars;');
  uimenu(findobj(gcf,'tag','helpm'),...           %menu items
   'Label','Help with MENU Items',...
   'Callback','helpopt;');
  uimenu(findobj(gcf,'tag','helpm'),...           %interactions
   'Label','Help with INTERACTIONS',...
   'Callback','helpint;');
  uimenu(findobj(gcf,'tag','helpm'),...           %output vars
   'Label','Help with OUTPUT VARIABLES',...
   'Callback','helpov;');
  uimenu(findobj(gcf,'tag','helpm'),...           %res plots
   'Label','Help with RESIDUAL PLOTS',...
   'Callback','helpplot;');
  uimenu(findobj(gcf,'tag','helpm'),...           %demo
   'Label','Run  glmlab  Demo',...
   'Callback','glmdemo',...
   'Separator','on');
  uimenu(findobj(gcf,'tag','helpm'),...           %where to get glmlab
   'Label','Where to get  glmlab',...
   'Callback','helpget;',...
   'Separator','on');
  uimenu(findobj(gcf,'tag','helpm'),...           %contact author
   'Label','How to Contact the Author',...
   'Callback','helpcont;');
  uimenu(findobj(gcf,'tag','helpm'),...           %splash screen
   'Label','Initial Splash Screen',...
   'Callback','glmsplsh(1);');
  uimenu(findobj(gcf,'tag','helpm'),...           %revision date
   'Label','Last Revision Date: 08 March 1999',...
   'Separator','on');
drawnow;                                           %faster to draw now

%UICONTROLS
set(findobj(gcf,'tag','glmlab_main'),...          %set some defaults
 'DefaultUIControlUnits','normalized',...
 'DefaultUIControlStyle','text');

%Title                                             
uicontrol(findobj(gcf,'tag','glmlab_main'),...    %title
 'String','glmlab',...
 'FontSize',12,...
 'Position',[0 0.95 1 0.05],...
 'FontWeight','bold',...
 'TooltipString','glmlab version 2.3.1',...
 'HorizontalAlignment','right')

%response (y) variable
uicontrol(findobj(gcf,'tag','glmlab_main'),...    %y entry
 'Style','Pushbutton',...
 'String','Response (y):',...
 'Callback','yventry;',...
 'Position',[.05 .80 .20 .08],...
 'TooltipString','Opens window to load response variable',...
 'HorizontalAlignment','left');
uicontrol(findobj(gcf,'tag','glmlab_main'),...    %y area
 'Style','edit',...
 'Max',3,'Min',1,...
 'Position',[.3 .80 .65 .08],...
 'Callback','yvarcont;',...
 'TooltipString','Enter the response variable name in here',...
 'tag','HYV');

%covariates (X)
uicontrol(findobj(gcf,'tag','glmlab_main'),...    % x entry
 'Style','Pushbutton',...
 'String','Covariates (X):',...
 'Callback','xventry;xvarcont;',...
 'HorizontalAlignment','left',...
 'TooltipString','Opens window to load covariates',...
 'Position',[.05 .7 .20 .08]);
uicontrol(findobj(gcf,'tag','glmlab_main'),...    %x area
 'Style','edit',...
 'Max',3,'Min',1,...
 'Position',[.3 .5 .65 .28],...
 'Callback','xvarcont;',...
 'TooltipString','Enter the list of covariates in here, one per row',...
 'tag','HXV');

%weight var
uicontrol(findobj(gcf,'tag','glmlab_main'),...    %weight entry
 'Style','Pushbutton',...
 'String','Prior Weights:',...
 'Callback','wventry;wvarcont;',...
 'HorizontalAlignment','left',...
 'TooltipString','Opens window to load prior weights',...
 'Position',[.05 .4 .20 .08]);
uicontrol(findobj(gcf,'tag','glmlab_main'),...    %weight area
 'Style','edit',...
 'Position',[.3 .4 .65 .08],...
 'Callback','wvarcont',...
 'TooltipString','Enter the prior weights variable name in here',...
 'tag','HPW');

%offset var
uicontrol(findobj(gcf,'tag','glmlab_main'),...    %offset entry
 'Style','Pushbutton',...
 'String','Offset Variable:',...
 'Callback','oventry;',...
 'HorizontalAlignment','left',...
 'TooltipString','Opens window to load offset variable',...
 'Position',[.05 .3 .20 .08]);
uicontrol(findobj(gcf,'tag','glmlab_main'),...    %offset area
 'Style','edit',...
 'Position',[.3 .3 .65 .08],...
 'Callback','ovarcont',...
 'TooltipString','Enter the offset variable name in here',...
 'tag','HOS');

%Bottom rows
uicontrol(findobj(gcf,'tag','glmlab_main'),...    %fit model
 'Style','Pushbutton',...
 'String','FIT SPECIFIED MODEL',...
 'Position',[.30 .05 .40 .1],...
 'Callback','fitscrpt',...
 'TooltipString','Fit model currently specified',...
 'Enable','off');                                  %initiall no model to fit

uicontrol(findobj(gcf,'tag','glmlab_main'),...    %new model
 'Style','Pushbutton',...
 'String','NEW MODEL',...
 'Position',[.05 .05 .20 .1],...
 'TooltipString','Declare New Model (before fitting to new data)',...
 'Callback','menuwork(8);');
uicontrol(findobj(gcf,'tag','glmlab_main'),...    %quit
 'Style','Pushbutton',...
 'String','QUIT glmlab',...
 'Position',[.75 .05 .20 .1],...
 'TooltipString','Quits glmlab',...
 'Callback','menuwork(50);');

%The file name of the file recording things
ddir=which('dummylog.m');

if isempty( ddir ),

   delete(gcf);
   delete(findobj('Name','glmlab Splash Screen'));
   
   disp(' Couldn''t find the file  dummylog.m.  Check the path.');
   disp(' This file should be placed somewhere so that I can write');
   disp(' to the directory in which it lives.');
   return;

end

GLMLAB_INFO_{8}=strrep(ddir,'dummylog.m','DETAILS.m'); %create path/file
if exist(GLMLAB_INFO_{8}),                         %delete if it already exists
   delete(GLMLAB_INFO_{8});
end;
%check that we have write permission to this directory

FID = fopen( GLMLAB_INFO_{8}, 'w');
if ( FID == -1 )
   disp([' Can''t create the file ', GLMLAB_INFO_{8}]);
   disp( ' Check that you have write permission.');
   disp( ' If not, move the file  dunnylog.m  to a place where you do.');
   return
end
clear FID


delete(findobj('tag','splash'));              %delete splash screen
set(findobj('tag','glmlab_main'),...          %set UserData as  GLMLAB_INFO_
 'Visible','on',...
 'UserData',GLMLAB_INFO_);
watchoff;                                     %watch off

figure( findobj('tag','glmlab_main'));        %make glmlab window the current window

set(findobj(gcf,'tag','glmlab_main'),...      %hide window from user
 'HandleVisibility','callback');
clear GLMLAB_INFO_  ddir                      %clear used vars from workspace
