%
%
%  Model approximation comparison
%
%                   Written by: Chriss Grimholt



% Main Simulink Paramaters

    simtime = 1500;

    steptime = 1;
    disturbancetime = 1;

    res = []; 

% Overshoot model approximation

for pmodel = [0.1 1 100 1000]   % process lag constants for different FOPTD
   
    

    
    stepvalue = 1;              % Step responce
    disturbancevalue = 0;
    
    gfeedback = tf(1);  % Closed-loop

    [gp_m kc0] = model(pmodel); % getting the FOPTD model

    gp = gp_m ;

    [kc0 fval]= fsolve(@(kc) fun(kc),kc0);  % gives overshoot = 0.3

    gc = controller (0, kc0, 0); % proportional controller 



sim('model_approx')

% Determining the approximated FOPTD model from different relations

[gp_om1 kp_om1 tp_om1 theta_om1] = omodel(kc0,y,r,t,1);
[gp_om2 kp_om2 tp_om2 theta_om2] = omodel(kc0,y,r,t,2);
[gp_om3 kp_om3 tp_om3 theta_om3] = omodel(kc0,y,r,t,3);
[gp_om4 kp_om4 tp_om4 theta_om4] = omodel(kc0,y,r,t,4);



% Determining the original and approximated FOPTD open-loop responces

stepvalue = 1;              % Step responce
disturbancevalue = 0;
    
gfeedback = tf(0);          % Open loop

gc = controller(0,1,0);

gp = gp_m;

sim('model_approx')

y_m=y;
t_m=t;

gp = gp_om1;

sim('model_approx')

y_om1=y;
t_om1=t;

gp = gp_om2;

sim('model_approx')

y_om2=y;
t_om2=t;

gp = gp_om3;

sim('model_approx')

y_om3=y;
t_om3=t;

gp = gp_om4;

sim('model_approx')

y_om4=y;
t_om4=t;


% Plotting the model responce

plot(t_m,y_m,t_om1,y_om1,t_om2,y_om2,t_om3,y_om3,t_om4,y_om4);
legend('model','corelation','0.43','0.305','old','location','best')

% calculating the model error

iae_om1=iae(t_m,y_m-y_om1);
iae_om2=iae(t_m,y_m-y_om2);
iae_om3=iae(t_m,y_m-y_om3);
iae_om4=iae(t_m,y_m-y_om4);

% Storing the results 

res = [res; iae_om1,iae_om2,iae_om3,iae_om4];

end

% Displaying the results

disp(res)
