%% Solutions for a set of different reduced oreder models

% Script for calculating worst case error, analyze it, plotting...
% WCE is calculating at the end of Nsim!!!
clc
clear all
close all

for Nsim =  10;
nfull = 16;
nred  = 4;
d01 = [];
d02 = [];
d0n = [];
    for i = 1:length(nred)
        % calculating WCE
        [objval(i) ur(:,i) uf(:,i) xr xf Nsim d0] = ...
            yalmip_useCHS_trajectory_check(nfull,nred(i),Nsim)
        d01 = [d01; d0(1,1)];
        d02 = [d02; d0(2,1)];
        d0n = [d0n; d0];
        
        % run analyze worst case of different reduced order models
        % (analyze if calculated worst case error is right = calculating worst case error of outputs using worst d0 using in MPC simulation (plotting closed loop simulation)) 
        [objvalsim(i),yfs,yrs] = analyze_dro(Nsim);
        diffobjvals(i) = objval(i) - objvalsim(i);
    end

objval_scaling = objval/Nsim;
% objvalsim_scaling = objvalsim/Nsim;
d01 = double(d01);
d02 = double(d02);

% plots to compare calculated WCE and WCE from MPC simulation

figure;
plot(nred,objval_scaling)
xlabel('states in reduced-order controller')
ylabel('worst case error (outputs)')
XLIM([1 16]);
title(['Nsim' num2str(Nsim)])

% figure;
% plot(nred,objvalsim_scaling)
% xlabel('states in reduced-order controller')
% ylabel('worst case error (outputs)')
% XLIM([1 16]);
% title(['Cloosed loop simulation Nsim' num2str(Nsim)])

%% save Nsimtest.mat nred objval objval_scaling
save(['Nsim' num2str(Nsim) '.mat'])
% save analyze_check;
end
