% Exact Local Method applied to three-product DWC
clear all; close all; clc;

global coldata dyndata hydraulic termodata UU alfa
% COLUMN DATA %%

% The script for calculating F matrix
%Script_Fmatrix                    
load F1

%Write specs after script_Fmatrix otherwise result might change
%Specs
load Nominal_final.mat
dyndata.u_nom = u_nom;

%Run the optimization

%[x_opt,fval,exitflag,output,lambda,Grad,Hessian] = fmincon(@(x) Objective(x),[dyndata.x_nom;dyndata.u_nom],Ain,bin,Aeq,beq,[],[],@(x) Petlyuk_nonlcon(x),options);

%x_nom=x_opt(1:225);u_nom=x_opt(226:end);

%dxdt = norm(Petlyuk_NLmodel(0,x_nom, u_nom));
%[sys Temp]=Petlyuk_NLmodel(0,x_nom,u_nom);
%Yo= Temp;
load Y0                            %Nominal Temperature
% Scaling of disturbances
% 10% deviaitions in F, zA, zB, 20% in Vmax and 10% in RV
dd=[0.01*dyndata.u_nom(6);0.01*dyndata.u_nom(7);0.01*dyndata.u_nom(8);...
    0.01*dyndata.u_nom(2);0.01*dyndata.u_nom(4)];
    %scaled with respect to Vmax
Wnd= diag(dd);
%Measurement error
%del=0.1;                                      %0.1 degree C
%Wn= 0.5*diag(ones(72,1));
Wn= 1*diag(zeros(72,1));                    % without noise

%Finding steady state gain matrix for three inputs L, Rl and S
%Run the file init_runner and obtain the value of GY as per instructions
load GY
%Y=[F1*Wnd Wn];
Y=[F1*Wnd  Wn];                              %  without noise
Hel=(inv(Y*Y')*(GY))';    %3X72
csel=Hel*Y0;
% or the combination can be made with the selected measurement only
load Juu.mat;
%Juu =eye(3);
load Jud.mat;
load GYd.mat;
M = sqrtm(Juu)*inv(Hel*GY)*(Hel*Y)
% Average loss is calculate dusing frobenius norm
Lavg = 0.5* norm(M,'fro')^2
%  0.0548
% Worst case loss is calculated using induced 2 norm
Lwc = 0.5* norm(M,2)^2
% 0.



