% Purpose:  Calculation and graphical representation of SIMC 
%           tuning performance
% Author:   Axel Lodemel Holene
% E-mail:   axel.holene@gmail.com
% Date:     April 2013
% About:    ctrl = [Kc I D]

%% Initialising
clear all
close all
clc

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

includeSmith = 1 ;

titleName = {'Case 1', 'Case 2', 'Case 3', 'Case 4',   ...
            'Case 5', 'Case 6', 'Case 7', 'Case 8',    ...
            'Case 9', 'Case 10', 'Case 11', 'Case 12', ...
            'Case 13'} ;
modelName = {'case1', 'case2', 'case3', 'case4', 'case5', ...
             'case6', 'case7', 'case8', 'case9', 'case10', ...
             'case11', 'case12', 'case13'} ;
if includeSmith
    cTypes  = {'po', 'simc', 'smith'} ;
else
    cTypes  = {'po', 'simc'} ;
end
ctrlrs  = {'pid', 'pi', 'p'} ;
cParm   = {'Chriss', 'Parallel', 'AltParallel', 'Cascade'} ;


for modelId = 1:9 %length(modelName)
    i = 1 ;                                             % Counter
    J = zeros(80,80) ;
    Ms = J ;
    Mt = J ;
    captions = {};
    for cType = 1:length(cTypes)
        for ctrlr = 1:length(ctrlrs)
            simcLoad = true ;
            for cNum = 1:length(cParm)
                innerLoop = true ;
                if cType == 3 && ctrlr == 1 && cNum == 4 
                    smithLoad = true ;     % Load Smith:Casc only
                elseif cType == 3 && ctrlr == 2
                    smithLoad = true ;
                elseif cType == 3
                    smithLoad = false ;
                    innerLoop = false ;
                end % ctrlr
                if cType == 2 && simcLoad
                    fprintf('Attempting to load %s \t\t', ...
                        strcat( upper(cTypes{cType}), ':', ...
                                upper(ctrlrs{ctrlr})))
                    try
                        load([mDir, '/results/', ...
                        num2str(cTypes{cType}), '/', ...
                        num2str(ctrlrs{ctrlr}), '/', ...
                        num2str(modelName{modelId}),'.mat'],...
                        'res')
                    catch
                        fprintf('Failed. \n')
                        innerLoop = false ;
                    end % try
                    if innerLoop 
                        simcLoad = false ; % already done
                    end
                elseif cType == 2 && ~simcLoad
                    innerLoop = false ;
                elseif cType == 3 && smithLoad && ctrlr == 3
                    fprintf('Attempting to load %s \t\t', ...
                        strcat( upper(cTypes{cType}), ':', ...
                                upper(ctrlrs{ctrlr})))
                    try
                        load([mDir, '/results/', ...
                        num2str(cTypes{cType}), '/', ...
                        num2str(ctrlrs{ctrlr}), '/', ...
                        num2str(modelName{modelId}),'.mat'],...
                        'res')
                    catch
                        fprintf('Failed. \n')
                        innerLoop = false ;
                    end % try
                    if innerLoop 
                        smithLoad = false ; % already done
                    end
                elseif cType == 3 && ~smithLoad && ctrlr == 3
                    innerLoop = false ;
                else
                    fprintf('Attempting to load %s \t\t', ...
                        strcat( upper(cTypes{cType}), ':', ...
                                upper(ctrlrs{ctrlr}), ':', ...
                                cParm{cNum}))
                    try
                        load([mDir, '/results/', ...
                        num2str(cTypes{cType}), '/', ...
                        num2str(ctrlrs{ctrlr}), '/', ...
                        num2str(cParm{cNum}),   '/', ...
                        num2str(modelName{modelId}),'.mat'],...
                        'res')
                    catch
                        fprintf('Failed. \n')
                        innerLoop = false ;
                    end % try
                end % if cType == 2
                if innerLoop
                    this = getfield(res, ...
                                strcat(upper(cTypes{cType}), ...
                                upper(ctrlrs{ctrlr}))) ;
                    if this.J(1) == 0
                        innerLoop = false ;% Dismiss zero cost vector
                        fprintf('Rejected. \n')
                    end
                else
                    fprintf('\n');
                end % innerLoop
                if innerLoop
                    if cType == 2
                        caption = strcat(upper(cTypes{cType}),...
                                ':', upper(ctrlrs{ctrlr})) ;
                    else
                        caption = strcat(upper(cTypes{cType}),...
                                ':', upper(ctrlrs{ctrlr}),':',...
                                cParm{cNum}) ;
                    end
                    captions{i} = caption ;
                    j = this.J ;
                    ms = this.Msc ;
                    mt = this.Mt ;
                    J(1:length(j),i) = j ;
                    Ms(1:length(ms),i) = ms ;
                    Mt(1:length(mt),i) = mt ;
                    fprintf('Success!\n') ;
                end
                i = i + 1 ;
            end
        end
    end
    % Removing zeros
    J(J==0)     = NaN ;
    Ms(Ms == 0) = NaN ;
    Mt(Mt == 0) = NaN ;
    captions = captions(~cellfun('isempty',captions)) ;
    ColorSet = varycolor(length(captions)) ;

     % Find SIMC reference
    for ctrlr = 1:2
        try
            load([mDir,'/results/simc/', ctrlrs{ctrlr}, '/', ...
                    modelName{modelId},'.mat'],'res') ;
            this =  getfield(res, ...
                    strcat(upper(cTypes{2}), ...
                    upper(ctrlrs{ctrlr}))) ;
            Jref = this.Reference.JcRef ;
            MsRef = this.Reference.MscRef ;
        catch
        end
    end
    % Plotting routine
    fprintf('Plotting')
    % J(Ms) plot
    figure(modelId)
    clf
    set(gca, 'ColorOrder', ColorSet);
    try
        hold on
        box on
        plot(Ms,J,'LineWidth',1)
        plot(MsRef,Jref,'ok')
        hold off
    catch
        plot(Ms, J, 'LineWidth', 1);
    end
    xlabel('Robustness, $M_s$', ...
           'interpreter','latex','FontSize',12)
    ylabel('Performance, $J$', ...
            'interpreter','latex','FontSize',12)
    title(titleName{modelId}, ...
            'interpreter','latex','FontSize',12)
    legend(captions, 'Location','NorthEast')

    if includeSmith
        save([mDir, '/results/merged/structs/incSmith/', ...
            num2str(modelName{modelId}),'.mat'])
        saveas(gcf,[mDir, '/results/merged/figures/incSmith/',...
           num2str(modelName{modelId}),'.fig'])
        loc = strcat(mDir, '/results/tex/incSmith/',...
                    num2str(modelName{modelId}),'.tex');
    else
        save([mDir, '/results/merged/structs/po_simc/', ...
            num2str(modelName{modelId}),'.mat'])
        saveas(gcf,[mDir, '/results/merged/figures/po_simc/',...
           num2str(modelName{modelId}),'.fig'])
        loc = strcat(mDir, '/results/tex/po_simc/',...
                    num2str(modelName{modelId}),'.tex');
    end
    matlab2tikz(loc, 'width', '\figureheight', 'height', ...
                '\figurewidth', 'showInfo', false) ;

    fprintf('.....')
    % Mt(Ms) plot
    figure(modelId+length(modelName))
    clf
    set(gca, 'ColorOrder', ColorSet);
    plot(Ms, Mt, 'LineWidth', 1)
    axis([0 3 0 3])
    xlabel('$M_s$', 'interpreter', 'latex', 'FontSize', 12)
    ylabel('$M_t$', 'interpreter', 'latex', 'FontSize', 12)
    title(titleName{modelId},'interpreter','latex','FontSize',12)
    legend(captions, 'Location','NorthEast')

        if includeSmith
        save([mDir, '/results/merged/structs/incSmith/', ...
            num2str(modelName{modelId}),'MsMt.mat'])
        saveas(gcf,[mDir, '/results/merged/figures/incSmith/',...
           num2str(modelName{modelId}),'MsMt.fig'])
        loc = strcat(mDir, '/results/tex/incSmith/',...
                    num2str(modelName{modelId}),'MsMt.tex');
    else
        save([mDir, '/results/merged/structs/po_simc/', ...
            num2str(modelName{modelId}),'MsMt.mat'])
        saveas(gcf,[mDir, '/results/merged/figures/po_simc/',...
           num2str(modelName{modelId}),'MsMt.fig'])
        loc = strcat(mDir, '/results/tex/po_simc/',...
                    num2str(modelName{modelId}),'MsMt.tex');
    end
    matlab2tikz(loc, 'width', '\figureheight', 'height', ...
                '\figurewidth', 'showInfo', false) ;
    fprintf('\t Finished!\n\n')
end                                             % Ending for-loop
restoredefaultpath