%% Calculation of WCE of outputs (full order controller and low order controller)
clc
clear all
close all

for Nsim =  10;
nfull = 16;
% nred  = 9; % Big Example 1
% nred  = 12; % Big Example 2
nred  = 14; % Big Example 3

d01 = [];
d02 = [];
d0n = [];
    for i = 1:length(nred)
        [objval(i) ur(:,i) uf(:,i) xr xf Nsim d0] = yalmip_MR_WCE(nfull,nred(i),Nsim)
        d01 = [d01; d0(1,1)];
        d02 = [d02; d0(2,1)];
        d0n = [d0n; d0];
    end

d01 = double(d01);
d02 = double(d02);

%% plot of WCE for different nred in last step of Nsim 
figure;
plot(nred,objval)
xlabel('states in reduced-order controller')
ylabel('worst case error (outputs)')
% XLIM([1 16]);
title(['Nsim' num2str(Nsim)])
grid on;
%% save Nsim.mat nred objval
save(['MR_Nsim' num2str(Nsim) '.mat'])
end

%% calculation and plot sum of WCE using MPC simulation and information from the end of Nsim

% calculate objsum of WCE for this Nsim and plot it 
figure;
Nsum = 10;  % lenght Nsum
for Nplot = Nsim
load(['MR_Nsim' num2str(Nplot) '.mat'])
[MRobjvalsum] = sum_MR_WCE(d01,d02,nfull,nred,Nsim,Nsum); 


plot(nred,MRobjvalsum)               %using nonscaling obj. fun
grid on
hold on
end

% plotting (labels, title, legend..)
xlabel('states in reduced-order controller')
ylabel('worst case error (outputs)')
title(['Nsim sum' num2str(Nsim)])
% XLIM([1 16]);

%% just plot plot sum of WCE for Nsim

% for Nplot = Nsim
% 
% load(['Objsum_MR_Nsim' num2str(Nplot) '.mat'])
% plot(nred,MRobjvalsum,'LineWidth',2)               %using nonscaling obj. fun
% hold on
% grid on
% end
% 
% % plotting (labels, title, legend..)
% 
% xlabel('states in reduced-order controller')
% ylabel('sum of worst case error (outputs)')
% title('Nsim 1-20');
% % XLIM([1 16]);

%% save data
% save MRWCE_E1
% save MRWCE_E2
save MRWCE_E3
