function Example_StepwiseTrace(history,varargin)
%EXAMPLE_STEPWISETRACE Plot stepwise regression history
%
% Syntax:
%
%   Example_StepwiseTrace(history)
%   Example_StepwiseTrace(history,param,val,...)
%
% Description:
%
%   Plots coefficient traces of the steps performed by STEPWISEFIT.
%
% Input Arguments:
%
%   history - Output structure of regression history from STEPWISEFIT.
%
% Optional Input Parameter Name/Value Pairs:
%
%   NAME      	VALUE
%
%   'varNames'	Cell vector of strings providing variable names for the
%               plot, of length equal to the number of original predictors
%               considered by STEPWISEFIT. Names are truncated to the first
%               five characters. The default is {'var1','var2',...}.
%
% Example:
%
%   load arrhythmia
%   [~,~,~,~,~,~,history] = stepwisefit(X,Y,'display','off');
%   Example_StepwiseTrace(history,'varNames',VarNames)
%
% See also STEPWISEFIT.

% Copyright 2012 The MathWorks, Inc.

% Parse inputs and set defaults:

parseObj = inputParser;
parseObj.addRequired('history',@historyCheck);
parseObj.addParamValue('varNames',{},@varNamesCheck);

parseObj.parse(history,varargin{:});

history = parseObj.Results.history;
varNames = parseObj.Results.varNames;

% Extract necessary information from the history:

B = history.B;
inModel = history.in;
everIn = any(inModel);
rmse = history.rmse;
MSE = (rmse).^2;

[numPreds,numSteps] = size(B);

% Create variable names:

if isempty(varNames)

    varNames =  strcat({'var'},num2str((1:numPreds)','%-u'));

else

    if length(varNames) < numPreds

        error(message('econ:Example_StepwiseTrace:VarNamesTooFew'))

    elseif length(varNames) > numPreds

        error(message('econ:Example_StepwiseTrace:VarNamesTooMany'))

    else

        % Truncate variable names to first five characters:
        varNames = cellfun(@(s)[s,'     '],varNames,'UniformOutput',false);
        varNames = cellfun(@(s)s(1:5),varNames,'UniformOutput',false);

    end

end

% Add initial zero coefficients, orient traces column-wise, and retain only
% those coefficients that are in the model at some step:

B = [zeros(1,numPreds);B'].*[zeros(1,numPreds);inModel];

% Create plot:

figure

subplot(5,1,1:4)
hold on
steps = 0:numSteps+1;
plotB = B(:,everIn);
set(gca,'ColorOrder',jet(sum(everIn)));
h = stairs(steps,[plotB;plotB(end,:)],'LineWidth',2);
plot(steps(end),plotB(end,:),'.','MarkerSize',18)
plot(steps,zeros(size(steps)),'k','LineWidth',2)
set(gca,'XTick',steps,'XTickLabel',{})
legend(h,varNames{everIn},'Location','Best') 
ylabel('Coefficient') 
title('{\bf Stepwise Trace}')
axis tight
grid on

subplot(5,1,5)
hold on
plot(steps(1:end-1),[NaN,MSE],'b.','MarkerSize',18);
plot(steps(end),MSE(end),'r.','MarkerSize',18);
set(gca,'XTick',steps)
set(gca,'XTickLabel',{steps(1:end-1),'Final'})
xlabel('Step')
ylabel('MSE')
axis tight
grid on

%-------------------------------------------------------------------------
% Check input history
function OK = historyCheck(history)
            
if ~isstruct(history)

    error(message('econ:Example_StepwiseTrace:HistoryNonStructure'))
      
elseif ~isfield(history,'B') || ~isfield(history,'rmse') || ~isfield(history,'in')

    error(message('econ:Example_StepwiseTrace:HistoryMissingRequiredField'))

else

    OK = true;

end

%-------------------------------------------------------------------------
% Check value of 'varNames' parameter
function OK = varNamesCheck(varNames)
    
if ~isvector(varNames)

    error(message('econ:Example_StepwiseTrace:VarNamesNonVector'))

elseif isnumeric(varNames) || (iscell(varNames) && any(cellfun(@isnumeric,varNames)))

    error(message('econ:Example_StepwiseTrace:VarNamesNumeric'))

else

    OK = true;

end