%--------------------------------------------------------------------------
%
% Kuramoto Sivashinsky equation
%
% LQR controller.
%
% An LQR controller is applied to the plant and tested when the system is
% excited by a white Gaussian noise d(t). The statistic of the velocity
% are computed and visualized in order to be compared to the other
% controlled cases.
% Saturation and actuator displecemnt are implemented: to activate
% uncomment the respective code lines.
%
% Reference figure(s): Fig. 11, Fig. 13, Fig. 14, Fig. 15, Fig. 22, Fig. 23
% 
% Nicolo' Fabbiane, March 2014
% KTH Mechanics
% nicolo@mech.kth.se
%
%--------------------------------------------------------------------------
clc, clear all
fprintf('\nLQR controller\n\n')




%% Initialization of the plant --------------------------------------------

% LTI system matrix A and x grid
nq = 400; % number of grid points

[A,x,I] = KS_init(nq);


% Inputs matrix B

% disturbance d (Gaussian shape at x_d with sigma_d variance)
x_d = 35; sigma_d = 4; 
Bd  = exp(-((x-x_d)/sigma_d).^2)/sigma_d;

% actuator u (Gaussian shape at x_u with sigma_u variance)
x_u = 400; sigma_u = 4; 
Bu  = exp(-((x-x_u)/sigma_u).^2)/sigma_u;


% Outputs matrix C

% measurement y (Gaussian shape at x_y with sigma_y variance)
x_y = 300; sigma_y = 4; 
Cy  = (exp(-((x-x_y)/sigma_y).^2)/sigma_y).' * I;

% output z (Gaussian shape at x_z with sigma_z variance)
x_z = 700; sigma_z = 4; 
Cz  = (exp(-((x-x_z)/sigma_z).^2)/sigma_z).' * I;




%% LQR controller ---------------------------------------------------------

Wz = 1.0e+0; % z-output weight
Wu = 1.0e+0; % control penalty

% Solution of the control Riccati equation (Eqn. 66)
X = care(A,Bu,Cz'*Wz*Cz,Wu);

% Control gains matrix K (Eqn. 65)
K = - Wu\Bu'*X;




%% Actuator displacement (uncomment to activate) --------------------------
% x_u = x_u + 5; 
% Bu = exp(-((x-x_u)/sigma_u).^2)/sigma_u;

        

        
%% Time integration -------------------------------------------------------

% Parameters
dt   = 1;
Tend = 50000;

Ton = 4000;

t  = 0:dt:Tend;
nt = length(t);


% Time-stepper matrices (Crank-Nicholson)
CNi = (speye(nq) - dt/2*A);
CNe = (speye(nq) + dt/2*A);


% Noise inizialization
d = randn(1,nt);     % unitary variance Gaussian white noise
d = d - mean(d,2);   % enforce zero-mean
d = d / std(d,[],2); % enforce unitary variance


% Variables initialization
v = zeros(nq,nt); % velocity
y = zeros(1 ,nt); % measurement signal
z = zeros(1 ,nt); % output signal
u = zeros(1 ,nt); % control signal


% Time-loop
for i = 1:nt-1
    
    % outputs
    y(:,i) = Cy*v(:,i);
    z(:,i) = Cz*v(:,i);
    
    % control forcing (Eqn. 55)
    if t(i) >= Ton
        u(:,i) = K*v(:,i);
    end
    
    % saturation (uncomment to activate)
    % u(:,i) = min([max([-2,u(:,i)]),2]);
    
    % timestep
    v(:,i+1) = CNi\(CNe*v(:,i) + dt * (Bd*d(:,i) + Bu*u(:,i)));
    
    % runtime output
    runtime_output

end




%% Velocity statistics ----------------------------------------------------
Tsta = 20000;
ista = (Tend-Tsta <= t) & (t <= Tend);

% Root-Mean-Square
v_rms = sqrt( mean(v(:,ista).^2,2) - mean(v(:,ista),2).^2 );

% visualization
rms_style  = '--k';
rms_legend = 'LQR';

plot_rms




%% Figure 11 --------------------------------------------------------------
figure(11); clf

plot(x,K,'-k','Linewidth',1.5);
ax = axis; axis([0 800 ax(3:4)])
xlabel('x'); ylabel('K(x)'); grid on





%% Figure 13 --------------------------------------------------------------
figure(13);

ax = [43500 45500 -3 3];
patch([ax(1:2) fliplr(ax(1:2))], [[1 1]*2 3 3], [.7 .7 .7],'EdgeColor','k'); hold on
patch([ax(1:2) fliplr(ax(1:2))],-[[1 1]*2 3 3], [.7 .7 .7],'EdgeColor','k')
plot(t,u,'--k','Linewidth',1.5); hold off
axis(ax)
xlabel('t'); ylabel('u(t)'); grid on




%% Figure 15a -------------------------------------------------------------
figure(15); 

subplot(2,1,1); plot(x,K,'--k','Linewidth',1.5); hold on
                ax = axis; axis([0 800 ax(3:4)])
                xlabel('x'); ylabel('K(x)'); grid on
