%% MPC results
clc;clear;%close all

load('outputMPC.mat')     % results from w1(Th-Thsp)^2 + w2(Fh-Fhsp)^2
warning off
load('outputSRCvsMPC.mat')% results from SRC

set(0,'DefaultTextFontName','Times',...
'DefaultTextFontSize',18,...
'DefaultAxesFontName','Times',...
'DefaultAxesFontSize',18,...
'DefaultLineLineWidth',1.5,...
'DefaultLineMarkerSize',7.75)

Fhmax = 3;
Fcmax = 10;
Tmax = 70+273.15; % for the scaled variales used in the MPC

Tc0 = [314.1411  310.3426  307.0824  304.2841  301.8823  299.8208  298.0514  296.5326  295.2291  294.1102];
Th0 = [335.2388  328.4495  322.6229  317.6224  313.3307  309.6473  306.4859  303.7724  301.4434  299.4442];
x0 = [Tc0;Th0];

%% SRC variables
Thout = Th(:,end)-273.15;
Fc = u1*Fcmax; % cold valve
Fh = u2*Fhmax; % hot valve
ThSP = 299.4442-273.15;

%% MPC variables
zc = [0.5; u_vec(:,1)];
zh = [1;u_vec(:,2)];
F_h = zh*Fhmax; 
F_c = zc*Fcmax;

T_c = [Tc0(1); x_vec(:,1)*Tmax]-273.15; % x_vec is scaled wrt Tmax
T_h = [ThSP; x_vec(:,20)*Tmax-273.15];

tgrid = 0:st:time;


figure('Name','MPC')
subplot(1,2,1)

%stairs(tgrid,F_c,'b')
stairs(tgrid,F_c,'Color',[0.4660 0.6740 0.1880],'Linewidth',1.5)
hold on
%stairs(tgrid,F_h,'r')
stairs(tgrid,F_h,'Color',[0.9290 0.6940 0.1250],'Linewidth',1.5)
plot(t,Fc, 'b-.')
plot(t,Fh,'r-.')
xlabel('Time (s)')
ylabel('Mass flow (kg/s)')
xlim([0 2000])
ylim([0 11])
legend('F_{C}^{MPC}','F_{H}^{MPC}','F_{C}^{SRC}','F_{H}^{SRC}','Location','northeast','Orientation','vertical')
title('Manipulated variables')
legend('boxoff')
hold off
% ax = gca;
% ax.FontSize = 14;
% ax.TickLabelInterpreter = 'latex';
% ax.Legend.Interpreter = 'latex';
% axes('position', [0.55 0.722481389578164 0.25 0.15]);
% %box on
% idx = 0<=tgrid & tgrid<150;
% plot(tgrid(idx), Fc(idx),'b','Linewidth',1)
% hold on
% plot(tgrid(idx), Fh(idx),'r','Linewidth',1)
% axis tight

subplot(1,2,2)
%stairs(tgrid,T_h,'r')
stairs(tgrid,T_h,'Color',[0.6350 0.0780 0.1840],'Linewidth',1.5)
hold on
plot(t, Thout, '-.', 'Color',[0.4940 0.1840 0.5560])
plot(t,ones(length(t),1)*ThSP,'k--','Linewidth',1)
xlabel('Time (s)');
ylabel('Temperature (^\circC)');
xlim([0 2000])
ylim([26 30])
legend('T_{H}^{MPC}','F_{C}^{SRC}','T_{H}^{SP}','Location','best','Orientation','vertical')
title('Controlled variable')
yticks(26:1:30)
legend('boxoff')

% ax = gca;
% ax.FontSize = 14;
% ax.TickLabelInterpreter = 'latex';
% ax.Legend.Interpreter = 'latex';
% axes('position', [0.2 0.274962779156327 0.25 0.15]);
% %box on
% plot(tgrid(idx), Th(idx),'r','Linewidth',1)
% axis tight

%% save figure
% print('-depsc2','-r600','MPCvsSRC.eps')

