% Exercise Example of retuning and initial oscillating feedback loop 
% with an initial wrong tuned PI-controller

clear all

k=1; tau=1;                  % Process model parameters, h_p(s)=k*e^(-tau*s)/s
Kp=0.005; Ti=8;              % Initial PI-tunings

% Old tuning
Kp_old=Kp; Ti_old=Ti;
kio1=Kp_old*Ti_old*k/4

s=tf('s')                    % Define Laplace operator

hc=Kp*(1+Ti*s)/(Ti*s);       % Define PI-controller transfer function
[num,den]=pade(tau,4);       % Define rational approximation to time delay, e^(-tau*s)
ht=tf(num,den);
hp=k*ht/s;                   % Process transfer function model, h_p(s)=k*e^(-tau*s)/s

h0=hc*hp;                    % Define loop transfer function, h_0(s)=h_c(s)*h_p(s)
h_ry=h0/(1+h0);              % Define transfer function from referencer, r, to output, y.
h_vy=-hp/(1+h0);             % define transfer function from disturbance, v, to output, y.

figure(1),                   % Plot step response for the initial tunings.
t=0:0.1:2000;
subplot(211), step(h_ry,t); ylabel('y/r'), grid
subplot(212), step(h_vy,t); ylabel('y/v'), grid
print -deps ex_oscillating

% Find retuned PI-controller parameter K_p for fixed Ti=6 as above.
% Use formula: T_i*K_p*k= 4*xi^2
% Compute relative damping factor for initial tuning
ki2=Kp*Ti*k/4;       % xi^2 = Kp*Ti*k/4 for initial tuning (li2=squared relative damping coeff.)
f=1/ki2              % New tuning: Kp:=Kp/xi^2

Kp=Kp*f              % Retuning of K_p

% Simulate retuned feedback loop step responses from, r and v to output, y.
hc=Kp*(1+Ti*s)/(Ti*s);
[num,den]=pade(tau,4);
ht=tf(num,den);
hp=k*ht/s;

h0=hc*hp;
h_ry=h0/(1+h0);
h_vy=hp/(1+h0);

figure(3), step(h_ry); 
figure(4), step(h_vy); 



