% Purpose:  Calculation and graphical representation of SIMC 
%           tuning performance
% Author:   Axel Lodemel Holene
% E-mail:   axel.holene@gmail.com
% Date:     May 2013
% About:    

%% Initialising
clear all
close all
clc

% Adding commonFiles to search path
mDir   = fileparts(pwd) ;
shared = fullfile(mDir,'commonFiles') ;     addpath(shared)
m2tkz  = fullfile(mDir,'matlab2tikz/src') ; addpath(m2tkz)
varclr = fullfile(mDir,'varycolor') ;       addpath(varclr)

titleName = {'Case 1,$ \G_{1}(s)=\gOne$',  ...
            'Case 2, $\G_{2}(s)=\gTwo$',  ...
            'Case 3, $\G_{3}(s)=\gThree$',...
            'Case 4, $\G_{4}(s)=\gFour$', ...
            'Case 5, $\G_{5}(s)=\gFive$', ...
            'Case 6, $\G_{6}(s)=\gSix$',  ...
            'Case 7, $\G_{7}(s)=\gSev$',  ...
            'Case 8, $\G_{8}(s)=\gEight$',...
            'Case 9, $\G_{9}(s)=\gNine$', ...
            'Case 10, $\G_{10}(s)=\gTen$', ...
            'Case 11, $\G_{11}(s)=\gElv$', ...
            'Case 12, $\G_{12}(s)=\gTwlv$',...
            'Case 13, $\G_{13}(s)=\gTh$', ...
            'Case 14, %\G_{14}(s)=\gFth$'} ;
modelName = {'case1', 'case2', 'case3', 'case4', 'case5', ...
             'case6', 'case7', 'case8', 'case9', 'case10', ...
             'case11', 'case12', 'case13','case14'} ;

cTypes  = {'po', 'simc', 'smith'} ;
ctrlrs  = {'pid', 'pi', 'brules','simc'} ;
cParm   = {'Chriss', 'Parallel', 'AltParallel', 'Cascade'} ;

for modelId = 10:14
    % Load PO values
    cType = 1 ;
    cNum = 4 ;        % Cascade only
    if modelId > 9
        ctrlrV = [2] ;
    else
        ctrlrV = [1 2] ;
    end
    Jpo = zeros(200,numel(ctrlrV)) ;
    Mspo = Jpo ;
    poCaptions = {} ;
    i = 1 ;
    for ctrlr = ctrlrV
        success = true ;
        lPath = strcat(mDir,'/results/', ...
                        cTypes{cType}, '/', ...
                        ctrlrs{ctrlr}, '/', ...
                        cParm{cNum},   '/', ...
                        modelName{modelId}) ;
        fprintf('Loading %s\n', lPath)
        try
            load([lPath,'.mat'],'res') ;
        catch
            fprintf('Failed: %s\n', lasterr)
            success = false ;
        end
        if success
            this = getfield(res, ...
                    strcat(upper(cTypes{cType}), ...
                    upper(ctrlrs{ctrlr}))) ;
            poCaptions{i} = strcat(cTypes{cType},':', ...
                            ctrlrs{ctrlr}) ;
            Jpo(1:length(this.J),i) = this.J ;
            Mspo(1:length(this.Msc),i) = this.Msc ;
            fprintf('Success! \n')
        end % success
        i = i + 1 ;
    end % ctrlr
    Jpo(Jpo==0)     = NaN ;
    Mspo(Mspo == 0) = NaN ;
    poCaptions = poCaptions(~cellfun('isempty',poCaptions)) ;

    % Load Smith
    cType = 3 ;         % Smith
    cNum = 4 ;          % Cascade only
    ctrlrV = [1 2] ;    % pid and pi
    Jsp = zeros(200,numel(ctrlrV)) ;
    Mssp = Jsp ;
    spCaptions = {} ;
    i = 1 ;
    for ctrlr = ctrlrV
        success = true ;
        lPath = strcat(mDir,'/results/', ...
                        cTypes{cType}, '/', ...
                        ctrlrs{ctrlr}, '/', ...
                        cParm{cNum},   '/', ...
                        modelName{modelId}) ;
        fprintf('Loading %s\n', lPath)
        try
            load([lPath,'.mat'],'res') ;
        catch
            fprintf('Failed: %s\n', lasterr)
            success = false ;
        end
        if success
            this = getfield(res, ...
                    strcat(upper(cTypes{cType}), ...
                    upper(ctrlrs{ctrlr}))) ;
            spCaptions{i} = strcat(cTypes{cType},':', ...
                            ctrlrs{ctrlr}) ;
            Jsp(1:length(this.J),i) = this.J ;
            Mssp(1:length(this.Msc),i) = this.Msc ;
            idx = find(this.Ms_span==1.6) ;
            tuneOut = [this.minTune(idx,:), ...
                       this.J(idx), ...
                       this.Msc(idx), ...
                       this.IAEtune(idx,:)] ;
            fprintf('%.2f\t%.2f\t%.2f\t%.2f\t%.2f\t%.2f\t%.2f\t%d\n',...
                    tuneOut, idx)
            dlmPath=strcat(mDir,'/results/merged/smithAll/',...
            'tuningtables/',modelName{modelId},cTypes{cType},...
            ctrlrs{ctrlr});

            dlmwrite([dlmPath,'.csv'],tuneOut,...
                    'precision','%.2f') ;
            fprintf('Success! \n')
        end % success
        i = i + 1 ;
    end % ctrlr
    Jsp(Jsp==0)     = NaN ;
    Mssp(Mssp == 0) = NaN ;
    Jsp(Jsp>100)   = 100 ;
    Mssp(Mssp>100) = 100 ;
    spCaptions = spCaptions(~cellfun('isempty',spCaptions)) ;

    % Load SIMC
    simcRef = {} ;
    cType = 2 ;
    if modelId > 9
        ctrlrV = [2] ;
    else
        ctrlrV = [1 2] ;
    end
    Jsimc = zeros(200,numel(ctrlrV)) ;
    Mssimc = Jsimc ;
    simcCaptions = {} ;
    i = 1 ;
    for ctrlr = ctrlrV
        success = true ;
        lPath = strcat(mDir,'/results/', ...
                cTypes{cType}, '/', ...
                ctrlrs{ctrlr}, '/', ...
                modelName{modelId}) ;
        fprintf('Loading %s\n', lPath)
        try
            load([lPath,'.mat'],'res') ;
        catch
            fprintf('Failed: %s\n', lasterr)
            success = false ;
        end
        if success
            this = getfield(res, ...
                    strcat(upper(cTypes{cType}), ...
                    upper(ctrlrs{ctrlr}))) ;
            simcCaptions{i} = strcat(cTypes{cType},':', ...
                            ctrlrs{ctrlr}) ;
            Jsimc(1:length(this.J),i) = this.J ;
            Mssimc(1:length(this.Msc),i) = this.Msc ;
            simcRef{ctrlr} = this.Reference ;
            eOut = [this.Reference.tau_cRef'...
                    this.Reference.RefTune  ...
                    this.Reference.JcRef'   ...
                    this.Reference.MscRef'  ...
                    this.Reference.iaeRef] ;
            sPath = strcat(mDir,'/results/merged/smithAll/', ...
                    'tuningComp/', modelName{modelId}, ...
                    ctrlrs{ctrlr}) ;
            dlmwrite([sPath,'.csv'], eOut, 'precision', '%.2f');
            fprintf('Success! \n')
            fprintf('Success! \n')
        end
        i = i + 1 ;
    end % ctrlr
    Jsimc(Jsimc==0)     = NaN ;
    Mssimc(Mssimc == 0) = NaN ;
    simcCaptions = simcCaptions(~cellfun('isempty',simcCaptions)) ;

    % Load Smith with rules
    cType = 3 ;
    smithRules = {'simc', 'brules'} ;
    smithRef = {} ;
    if modelId > 9
        ctrlrV = [2] ;
    else
        ctrlrV = [1 2] ;
    end
    JsmithR = zeros(200,numel(ctrlrV)) ;
    MssmithR = JsmithR ;
    smithRCaptions = {} ;
    i = 1 ;
    for ctrlr = ctrlrV
        success = true ;
        lPath = strcat(mDir,'/results/', ...
                cTypes{cType},    '/', ...
                              'simc/', ...
                ctrlrs{ctrlr},    '/', ...
                modelName{modelId}) ;
        fprintf('Loading %s\n', lPath)
        try
            load([lPath,'.mat'],'res') ;
        catch
            fprintf('Failed: %s\n', lasterr)
            success = false ;
        end
        if success
            this = getfield(res,'JMs') ;
            smithRCaptions{i} = strcat(cTypes{cType},':', ...
                          'simc:',ctrlrs{ctrlr}) ;
            JsmithR(1:length(this.J),i) = this.J ;
            MssmithR(1:length(this.Ms),i) = this.Ms ;
            smithRef{ctrlr} = res.Reference ;
            fprintf('Success! \n')
        end
        i = i + 1 ;
    end % ctrlr
    JsmithR(JsmithR==0)     = NaN ;
    MssmithR(MssmithR == 0) = NaN ;
    smithRCaptions = smithRCaptions(~cellfun('isempty',smithRCaptions)) ;

    % Plotting routine
    fprintf('Plotting')
    % Compare PO and Smith:PO
    figure(modelId) ;
    clf
    box on
    hold on
    plot(Mspo, Jpo, Mssp, Jsp)
    % plot(Mssp,Jsp)
    caption = [poCaptions spCaptions] ;
    legend(caption,'location','NorthEast')
    hold off
    % 
    xlabel('Robustness, $\Ms$', ...
           'interpreter','latex')
    ylabel('Performance, $J$', ...
            'interpreter','latex')
    title(titleName{modelId}, ...
            'interpreter','latex')
    axis([1 2 0 20])
    sPath = strcat(mDir,'/results/merged/smithAll/poComp/', ...
                    modelName{modelId}) ;
    save([sPath,'.mat'])
    saveas(gcf,[sPath,'.fig'])
    matlab2tikz([sPath,'.tex'], 'showInfo', false) ;

    % Compare Smith:PO and Smith:rules
    figure(modelId + length(modelName)) ;
    clf
    box on
    hold on
    plot(Mssp,Jsp, MssmithR, JsmithR)
    if modelId < 10
        plot(NaN,NaN,NaN,NaN,...
            smithRef{1}.MsRef,smithRef{1}.Jref,'o', ...
            smithRef{2}.MsRef,smithRef{2}.Jref,'o' )
    else
        plot(NaN,NaN, smithRef{2}.MsRef,smithRef{2}.Jref,'o' )
    end
    caption = [spCaptions smithRCaptions] ;
    legend(caption,'location','NorthEast')
    % for n = 1:2
    %     try
    %         a = smithRef{n} ;
    %         plot(a.MsRef,a.Jref,'o')
    %     catch
    %     end
    % end % for
    hold off
    %
    xlabel('Robustness, $\Ms$', ...
           'interpreter','latex')
    ylabel('Performance, $J$', ...
            'interpreter','latex')
    title(titleName{modelId}, ...
            'interpreter','latex')
    axis([1 2 0 20])
    sPath = strcat(mDir,'/results/merged/smithAll/tuningComp/',...
                    modelName{modelId}) ;
    save([sPath,'.mat'])
    saveas(gcf,[sPath,'.fig'])
    matlab2tikz([sPath,'.tex'], 'showInfo', false) ;
    fprintf('\t Finished!\n\n')
end % modelId
restoredefaultpath