
clear fig
close all
clc

% Load of the saved files
if ~exist('err','var')
    load('LocalSave\Paper\Rea_20180307_AddSamp_diff_w_5e3.mat')
end

% Calculation of several values
Ver.Ind = 'MolFrac';
opt.comptresh = 0.02;
opt.normtresh = 0.05;
n.norm = 5;
var_fit = [3 4];

ind.NN = [1:Np.d(1)/Np.c:(Np.NNt(1)-Np.a)/Np.c+1 ...
          (Np.NNt(1)-Np.a+Np.d(2))/Np.c+1:Np.d(2)/Np.c:(Np.NNt(2)-Np.a)/Np.c+1 ...
          (Np.NNt(2)-Np.a+Np.d(3))/Np.c+1:Np.d(3)/Np.c:n.PLS];
      
% Selection of the chosen data points
switch Ver.Ind
case 'MolFlow'
    U.ini.sel = U.ini.samp;
    U.tra.sel = U.tra.samp;
case 'MolFrac'
    U.ini.sel = U.ini.Molfrac;
    U.tra.sel = U.tra.Molfrac;
case 'PartPress'
    U.ini.sel = U.ini.PartPress;
    U.tra.sel = U.tra.PartPress;
end

% Claculation of the norms
if ~exist('norm_comb_mean_f','var') || isempty(norm_comb_mean_f{2})
    
% Predefinition of the matrices
if true
    xload      = cell(n.PLS,n.red);
    yload      = xload;
    xloads     = xload;
    load_used  = xload;
    xscores    = xload;
    yscores    = xload;
    stats      = xload;
    beta       = xload;
    pctvar     = xload;
    sumpct     = xload;
    diff_loads = xload;
    diff_mat   = cell(n.in,n.red);
    
    % 1-norm
    norm_comb_1           = xload;
    norm_comb_mean_1      = xloads;
    norm_comb_mean_1(1,:) = num2cell(ones(1,n.red));
    
    % 2-norm
    norm_comb_2           = xload;
    norm_comb_mean_2      = xloads;
    norm_comb_mean_2(1,:) = num2cell(ones(1,n.red));
    
    % inf-norm
    norm_comb_i           = xload;
    norm_comb_mean_i      = xloads;
    norm_comb_mean_i(1,:) = num2cell(ones(1,n.red));
    
    % frob-norm
    norm_comb_f           = xload;
    norm_comb_mean_f      = xloads;
    norm_comb_mean_f(1,:) = num2cell(ones(1,n.red));
    
    norm_loads = cell(n.PLS,n.red,n.in);
    norm_loads_mean = norm_loads;
    optpls = statset('UseParallel',true);
end
    
for k = 1:n.PLS
    
    for j = 1:n.red     
        
        % Scaling of the independent variables
        [U.tra.scaled,Var.U.mu,Var.U.std] = zscore(U.tra.sel(1:Np.tot(k),:));

        % Scaling of the dependent variables
        [x.tra.scaled,Var.x.mu,Var.x.std]  = zscore(x.tra.red(1:Np.tot(k),j));
        
        % Calculation of the Partial least square regression
        [xload{k,j},yload{k,j},xscores{k,j},yscores{k,j},...
                 beta{k,j},pctvar{k,j},~,stats{k,j}] = plsregress(U.tra.scaled,x.tra.scaled,n.in,'options',optpls);
         
        load_used{k,j} = stats{k,j}.W;xload{k,j};%/(xload{k,j}'*xload{k,j});  
        % Rearrangement and normalization of the loads
%         xloads{k,j} = load_used{k,j}./(ones(n.in,1)*max(abs(load_used{k,j})));
        xloads{k,j} = load_used{k,j}./(ones(n.in,1)*sqrt(diag(stats{k,j}.W'*stats{k,j}.W)'));
        sumpct{k,j} = sum(pctvar{k,j}(2,:) > opt.comptresh);
        if k > 1
            diff_loads{k,j} = (xloads{k,j}-xloads{k-1,j});
            
            % 1-norm
            norm_comb_1{k,j}   = norm(diff_loads{k,j}(:,1:min(sumpct{k,j},sumpct{k-1,j})),1);
            norm_comb_mean_1{k,j} = mean(cell2mat(norm_comb_1(max(k-n.norm,1)+1:k,j)));
            
            % 2-norm
            norm_comb_2{k,j}   = norm(diff_loads{k,j}(:,1:min(sumpct{k,j},sumpct{k-1,j})),2);
            norm_comb_mean_2{k,j} = mean(cell2mat(norm_comb_2(max(k-n.norm,1)+1:k,j)));
            
            % inf-norm
            norm_comb_i{k,j}   = norm(diff_loads{k,j}(:,1:min(sumpct{k,j},sumpct{k-1,j})),inf);
            norm_comb_mean_i{k,j} = mean(cell2mat(norm_comb_i(max(k-n.norm,1)+1:k,j)));
            
            % inf-norm
            norm_comb_f{k,j}   = norm(diff_loads{k,j}(:,1:min(sumpct{k,j},sumpct{k-1,j})),'fro');
            norm_comb_mean_f{k,j} = mean(cell2mat(norm_comb_f(max(k-n.norm,1)+1:k,j)));
            for l = 1:n.in
                norm_loads{k,j,l} = norm(diff_loads{k,j}(:,l),'fro');
                norm_loads_mean{k,j,l} = mean(cell2mat(norm_loads(max(k-n.norm,1)+1:k,j,l)));
                diff_mat{l,j}(:,k) = diff_loads{k,j}(:,l);
            end
        end
    end
    
    if mod(Np.tot(k),100) == 0
        fprintf('%i points are sampled.\n',Np.tot(k))
    end
    
end
end

% Definition of integer values
itg.fig = 1;
itg.lab = 1;
itg.fda = 1;
itg.axe = 1;
itg.ann = 1;

% Definition of figure and values
fig.dimw12 = 12.3;  % 12.5 for ESCAPE
fig.dimh12 = 5.5;
fig.dimw21 = 8.4;
fig.dimh21 = 12;
fig.dimw = 8.4;
fig.dimh = 6;
fig.Font = [10 8];
fig.label = [];
fig.ann   = [];
k = 1;

fig.in(itg.fig) = figure(itg.fig);
set(fig.in(itg.fig),'units','centimeters','position', [5+itg.fig,5+itg.fig, fig.dimw12, fig.dimh12]);
% Np.tot(ind.NN([16 20 32 52]))
% Plot of the evaluation of the value with the maximum load
for j = var_fit
    subplot(1,2,k)
    fig.axes(itg.axe) = gca;
    err.test = cell2mat(err.val_comb(:,j)');
    hold on
%     fig.dat(itg.fda) = plot(cell2mat(norm_comb_mean_1(ind.NN(2:end),j,1)),err.test(2,2:end),'k'); itg.fda = itg.fda+1;
%     fig.dat(itg.fda) = plot(cell2mat(norm_comb_mean_2(ind.NN(2:end),j,1)),err.test(2,2:end),'r'); itg.fda = itg.fda+1;
    fig.dat(itg.fda) = plot(cell2mat(norm_comb_mean_f(ind.NN(2:end),j,1)),err.test(2,2:end),'k'); itg.fda = itg.fda+1;
    fig.dat(itg.fda) = plot(cell2mat(norm_comb_mean_f(ind.NN([16 20 32 52]),j,1)),err.test(2,[16 20 32 52]),'ko','MarkerSize',10); itg.fda = itg.fda+1;
%     fig.dat(itg.fda) = plot(cell2mat(norm_comb_mean_i(Np.totNN(2:end),j,1)),err.test(2,2:end),'y'); itg.fda = itg.fda+1;
    if j == 3
        fig.dat(itg.fda) = plot(opt.normtresh*[1 1],5*10.^[-3 0],'k--','LineWidth',0.5); itg.fda = itg.fda+1;
        fig.axes(itg.axe).YTick = 10.^(-2:1:0);
        fig.axes(itg.axe).YLim  = 5*10.^[-3 0];
        fig.axes(itg.axe).Position = [.10 .17 .375 .78];
        fig.label(itg.lab) = ylabel('$\overline{\left|\epsilon\right|}$ of $y_3 = \xi$ [mol/s]'); itg.lab = itg.lab+1;
        fig.ann(itg.ann) = annotation('textbox',[0 .95 .05 .05],'String','a)'); itg.ann = itg.ann+1;
        fig.ann(itg.ann) = annotation('textbox',[.22 .90 .05 .05],'String','$\gamma$'); itg.ann = itg.ann+1;
        fig.ann(itg.ann) = annotation('textbox',[.36 .85 .05 .05],'String','$n_p = 100$'); itg.ann = itg.ann+1;
        fig.ann(itg.ann) = annotation('textbox',[.32 .54 .05 .05],'String','$n_p = 200$'); itg.ann = itg.ann+1;
        fig.ann(itg.ann) = annotation('textbox',[.26 .27 .05 .05],'String','$n_p = 500$'); itg.ann = itg.ann+1;
        fig.ann(itg.ann) = annotation('textbox',[.10 .32 .05 .05],'String','$n_p = 1000$'); itg.ann = itg.ann+1;
    elseif j == 4
        fig.dat(itg.fda) = plot(opt.normtresh*[1 1],[1 5].*10.^[0 3],'k--','LineWidth',0.5); itg.fda = itg.fda+1;
        fig.axes(itg.axe).YTick = 10.^(-0:1:3);
        fig.axes(itg.axe).YLim  = [1 5].*10.^[0 3];
        fig.axes(itg.axe).Position = [.6 .17 .375 .78];
        fig.label(itg.lab) = ylabel('$\overline{\left|\epsilon\right|}$ of $y_4 = Q_{HEx5}$ [kW]'); itg.lab = itg.lab+1;
        fig.ann(itg.ann) = annotation('textbox',[.50 .95 .05 .05],'String','b)'); itg.ann = itg.ann+1;
        fig.ann(itg.ann) = annotation('textbox',[.72 .90 .05 .05],'String','$\gamma$'); itg.ann = itg.ann+1;
        fig.ann(itg.ann) = annotation('textbox',[.78 .75 .05 .05],'String','$n_p = 100$'); itg.ann = itg.ann+1;
        fig.ann(itg.ann) = annotation('textbox',[.82 .44 .05 .05],'String','$n_p = 200$'); itg.ann = itg.ann+1;
        fig.ann(itg.ann) = annotation('textbox',[.76 .26 .05 .05],'String','$n_p = 500$'); itg.ann = itg.ann+1;
        fig.ann(itg.ann) = annotation('textbox',[.60 .31 .05 .05],'String','$n_p = 1000$'); itg.ann = itg.ann+1;
    end
    fig.label(itg.lab) = xlabel('Norm $\left|\left|\Delta\mathbf{W}^k\right|\right|_F^{av}$'); itg.lab = itg.lab+1;
    fig.axes(itg.axe).XLim  = [5 1].*10.^[-3 0];
    fig.axes(itg.axe).XScale = 'log';
    fig.axes(itg.axe).YScale = 'log';
    itg.axe = itg.axe+1;
    k = k+1;
end
itg.fig = itg.fig+1;


set(fig.ann,  'Interpreter', 'Latex');
set(fig.ann,  'Fontsize', fig.Font(2));
set(fig.ann,  'LineStyle', 'none');
set(fig.label,'Fontsize', fig.Font(1));
set(fig.label,'Interpreter', 'Latex');
set(fig.axes, 'FontSize', fig.Font(2));
set(fig.axes, 'Box','on');
set(fig.axes, 'TickLabelInterpreter', 'Latex');
set(fig.axes, 'TickLabelInterpreter', 'Latex');
set(fig.axes, 'LineWidth',.75);
set(fig.axes, 'XMinorTick', 'on');
set(fig.dat,  'LineWidth',.75)

