% Main file to compare feedback linearization, chain of transformations and
% cascade transformation and normal cascade for heated tanks in series
% since 21.01.2021

clc;clear;close all
%% Plotting options
set(0,'DefaultTextFontName','Times','DefaultTextFontSize',14,...
    'DefaultAxesFontName','Times','DefaultAxesFontSize',14,...
    'DefaultLineLineWidth',4,'DefaultLineMarkerSize',7.75,...
    'DefaultStairLineWidth',2)
%% Parameters
F  = 10;                                                  % [kg/s] flowrate
m1 = 1000;                                           % [kg]holdup in tank 1
m2 = 1500;                                          % [kg] holdup in tank 2
cp = 4.18;                                      % [kJ/kg/deg] specific heat
p  = [F;m1;m2;cp];                                    % vector of paramters
%% States
T10 = 50;                                            % temperature in tank 1
T20 = 70;                                            % temperature in tank 2
x0  = [T10;T20];                                          % initial conditions
%% Disturbances
T00 = 10;                                                % inlet temperature
Q20 = -F*cp*(T10-T20);                                  % [kW] heat to tank 1

%% Input
Q10 = -F*cp*(T00-T10);                                  % [kW] heat to tank 1

%% Tuning parameter tau
tau01 = m1/F;                                            % [sec] for tank 1
tau02 = m2/F;                                            % [sec] for tank 2
p = [p;tau01;tau02];             % add tuning parameter to parameter vector
nx=2;nu=1;nd=2;np=length(p);                      % number of each variable

%% Set-up simulation
tsim = 1000;                                           % [s] simulation time
tQ1  = 100;                     % [s] step in input for open loop response
tdT0 = 10;                                           % [s] step time for T0
tdQ2 = 10;                                           % [s] step time for Q2
tsp  = 10;
dQ1  = Q10-0.1*Q10;                    % [kW] step in Q2 for open loop response
dT0  = T00+0;                                           % [degC] step in T0
dQ2  = Q20+0;                                           % [degc] step in Q2

%% Simulate cascade
v20   = T20;  dv2 = v20+0; % setpoint
k     = 0.24; tau = 100; tauC = tau/10; theta = 0;% from open loop response
KcC   = 0; %1/k*tau/(tauC+theta);                             % proportional gain
tauIC = 1; %min(tau,4*(tauC+theta));                            % integral time

% sim('simCascade')
% figure();plot(time,Q1); xlabel('Time [s]'); ylabel('Original input');
% legend('Q1');
% figure();
% plot(time,v2); xlabel('Time [s]'); ylabel('Transformed input');
% legend('v2'); 

%% Simulate chain of transformations

%sim('simChain')

%% Simulate feedback linearization
v20   = 0;  dv2 = v20+0; % setpoint
sim('simFbLin')

