% main_sim_1st_margins.m
% Using SIMC PI controller tuning rules for a 1st. order + time delay
% plant and calculate the gain and phase margins, GM and PM, respectively.
% Checking the interpretations multiplicative gain uncertainty and additive
% time delay error uncertainty.
% 

K=1; tau=1; T=1;          % The nominal plant model parameters.

s=tf('s');
hp=K*exp(-tau*s)/(1+T*s); % The plant model transfer function.

% SIMC tuning rules
Tc=tau;                   % The user specified tuning parameter.
Kp=T/(K*(Tc+tau));        % The proportional gain.
Ti=min(T,4*(Tc+tau));     % The integral time constant.
hc=Kp*(1+Ti*s)/(Ti*s);    % PI controller transfer function.

% The margins
h0=hc*hp;
[GM,PM,w180,wc]=margin(h0)

% Check the Gain Margin and multiplicative unc. at w180.
K_true=GM*K;              % Max multiplicative gain uncertainty.
hp_true=K_true*exp(-tau*s)/(1+T*s);
h0_true1=hp_true*hc;
[GM1,PM1,w1801,wc1]=margin(h0_true1)  % At the stability limit

% Check the Phase Margin and uncertainty in the time delay, at wc.
dt_max=(PM*pi/180)/wc;                  % Max time delay error at wc.
hp_true=K*exp(-(tau+dt_max)*s)/(1+T*s);
h0_true2=hp_true*hc;
[GM2,PM2,w1802,wc2]=margin(h0_true2)    % At the stability limit

% Checking both gain and time delay uncertainties
hp_true=0.4*K_true*exp(-(tau+dt_max*0.4)*s)/(1+T*s);
h0_true3=hp_true*hc;
[GM3,PM3,w1803,wc3]=margin(h0_true3)    % At the stability limit
T3=h0_true3/(1+h0_true3); step(T3)