% Process control course  Exercise 2
%
%  This script initiallizes the necessary parameters and runs the simulink
%  model for task 4
% 
clear all
clc
warning off
% Initializing
dist_feed_time=10 ; feed_dist=0.0 ; dist_comp_time=50; comp_dist=0.0;
Vb_change_time=10; Vb_step=3.55; D_change_time=30; D_step=0.5*1.0; 
B_change_time=40; B_step=0.5*1.0; setpoint_time=10; xd_sp=0.8;
LT_change_time=10; LT_step=3.05*1.0; Vb_change_time=10;
Vb_step=3.55*1.0; D_change_time=10; D_step=0.5*1.0; B_change_time=10;
B_step=0.5*1.0;
%Level controllers are working 
%Top level controller
Kd=-10;
%Bottom level controller
Kb=-10;




% ==========Test your controller here!================

%-----------------Here you set  the PI controller parameters that you found
Kc=25;   % proportional gain
taui=6;  % integral time
%------------------------------------------------------

% CV setpoints
%When x_D setpoint will change
setpoint_time=70;
%x_D setpoint after change
xd_sp=0.92;

%When the disturbance in feed happens
dist_feed_time=40;
%The size of feed disturbance 
feed_dist=0.1;

%When the disturbance in feed composition happens
dist_comp_time=10;
%The size of feed composition disturbance
comp_dist=0.1;


%Simulate closed loop system
sim('simdist.mdl')

xd=x_out(:,4);
xb=x_out(:,1);

%======== Plot results ===============

figure(2)
subplot(211)
plot(time,xd)
set(gca,'FontSize',14)
title('Closed-loop evaluation')
ylabel('Top composition')

x=[setpoint_time setpoint_time];
y=[min(xd) 0.95];
hold on
plot(x,y,'k-.')

text(setpoint_time+1,0.93,...
     '\leftarrow xd_{SP}+2%',...
     'FontSize',12)

x=[dist_feed_time dist_feed_time];
y=[min(xd) 0.95];
hold on
plot(x,y,'k-.')

text(dist_feed_time+1,0.93,...
     '\leftarrow F+0.1',...
     'FontSize',12)
 
 
 x=[dist_comp_time dist_comp_time];
y=[min(xd) 0.95];
hold on
plot(x,y,'k-.')

text(dist_comp_time+1,0.93,...
     '\leftarrow zF+0.05',...
     'FontSize',12)
  ylim(y)
 
subplot(212)
plot(time,Lt)
set(gca,'FontSize',14)
xlabel('Time, [min]')
ylabel('Reflux LT')
axis tight