% LINRED.M %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% Linearize and reduce the nonlinear Kaibel model for use in MPC as a
% prediction model

init;

red_order = 30;

ts = 10;

disp('Linearizing model...');
[A_lin,B_lin,C_lin,D_lin] = linmod('kaibel_openloop',dyndata.x_nom,dyndata.u_nom);

C_lin = [
    C_lin(17 + 6,:)
    C_lin(30 + 6,:)
    C_lin(59 + 6,:)
    C_lin(49 + 6,:)
    C_lin(6 + 6,:)
    C_lin(53 + 6,:)
    C_lin(24 + 6,:)
    ];

% Remove states for holdup in reboiler and condenser
A_lin = [
    A_lin(1:336,1:336)      A_lin(1:336,339:341)
    A_lin(339:341,1:336)    A_lin(339:341,339:341)
    ];
B_lin = [
    B_lin(1:336,:)
    B_lin(339:341,:)
    ];
C_lin = [
    C_lin(:,1:336)          C_lin(:,339:341)
    ];

B_lin = [B_lin(:,5),B_lin(:,1),B_lin(:,3),B_lin(:,4),B_lin(:,2),B_lin(:,6),B_lin(:,7),B_lin(:,8),B_lin(:,9),B_lin(:,10),B_lin(:,11)];

D_lin = zeros(size(C_lin,1),size(B_lin,2));

disp('Reducing model...');

reduced_system = balred(ss(A_lin,B_lin,C_lin,D_lin),red_order,'Elimination','Truncate');

discrete_system = c2d(reduced_system,ts);

A = discrete_system.a;
B = discrete_system.b(:,1:4);
C = discrete_system.c;
Bd = discrete_system.b(:,5:end);
D = zeros(7,4);

clear A_lin B_lin C_lin D_lin discrete_system reduced_system
