%Exact local method for the set of  three temperatures obtained from branch
%and bound Cao & Kariwala 2008
% This method has been used here to prescreen the candidate controlled
% variables
% Exact Local Method applied to three-product DWC

clear all; close all; clc;

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

% The script for calculating F matrix
%Script_Fmatrix                    % This gives an average loss 0.0455 and
load F1
%same as F1

load Nominal_final.mat
dyndata.u_nom = u_nom;

load Y0                            %Nominal Temperature
% Scaling of disturbances
% 10% deviaitions in F, zA, zB, 10% 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                                    
%0.5 degree C
Wn= 0.5*diag(ones(3,1));
%Wn= 1*diag(zeros(3,1));                    % without noise

%sset = [10 38 60];             % 1st rank  
%sset = [9 38 60];             % 2ndt rank
%sset = [11 38 60];             % 3rd  rank
%sset = [10 38 63];             % 4th  rank
%sset = [8 38 60];             % 5th  rank
%sset = [9 38 63];             % 6th  rank
%sset = [7 38 60];             % 7th  rank
%sset = [10 38 59];             % 8th  rank
%sset = [13 38 62];             % 9th rank
%sset = [11 38 63];             % 10th rank

% The best ten sets of temperatures as obtained by  average loss
% calculation by Cao and Kariwala
%sset = [9 38 59];         %1st best
%sset = [9 38 58];        %2nd best
%sset = [9 39 59];        %3rdd best
%sset =  [39 57 63];        %4th best
%sset = [9 39 58];        %5th best
%sset = [8 38 59];        %6th best
%sset = [8 38 58];        %7th best
%sset = [8 39 59];        %8th best
%sset = [10 39 59];        %9th best
%sset = [10 38 58];        %10th best


%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
GY3 = GY(sset,:);
F3 =F1(sset,:);
Y3=[F3*Wnd  Wn];                              %  without noise
Hel3=(inv(Y3*Y3')*(GY3))';    %3X72
%csel3=Hel3*Y0(sset),:);
% or the combination can be made with the selected measurement only

% Evaluation of loss using exact local method
load Juu.mat;
%Juu =eye(3);
load Jud.mat;
%load GYd.mat;

M3 = sqrtm(Juu)*inv(Hel3*GY3)*(Hel3*Y3)

%M = sqrt([1861 0 0; 0 1160 0;0 0 1.84])*inv(Hel*GY)*Hel*Y
% Average loss is calculate dusing frobenius norm
Lavg = 0.5* norm(M3,'fro')^2
%  0.0548
% Worst case loss is calculated using induced 2 norm
Lwc = 0.5* norm(M3,2)^2
% 0.
