% Delivered to the Government in Accordance with Contract FA8650-10-C-7080
% 
%  (c) 2011 United Technologies Corp.
% Developed with the sponsorship of the Defense Advanced Research Projects Agency (DARPA).
%  
% Permission is hereby granted, free of charge, to any person obtaining a copy of this data, including any software or models in source or binary form, as well as any drawings, specifications, and documentation (collectively "the Data"), to deal in the Data without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Data, and to permit persons to whom the Data is furnished to do so, subject to the following conditions:
%  
% The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Data.
%  
% THE DATA IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS, SPONSORS, DEVELOPERS, CONTRIBUTORS, OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE DATA OR THE USE OR OTHER DEALINGS IN THE DATA.
% 


%This is a shell to capture the demo for META 2 program on Mar22, 2011
clear all;close all;
clc;
%Different computation blocks are performed sequentially for ease of debugging. Once tested, we can plug all evaluations within a single loop for better efficiency.
%
%
%Architecture enumeration and DSM generation block could be included here or could be a seperate process altogether.
%
%clock
RLC_AE_DSM_script
%
%
%Architecture enumeration and DSM generation ends here.
%
%
%Structural Complexity metric calculation performed here...
base = 'Arch_RLC_DSM_'; %base filename
N = num_enumerated_architectures;   %number of generated architectures
arch=[1:1:N];
complexity=zeros(N,1);
num_connections=zeros(N,1);
num_components=zeros(N,1);
arch_array{1,N}=[];
file_extension='.csv';
%sheet='DSM';
%
disp(['Processing ',num2str(N),' architecture']);
t2=[];
h = waitbar(0,['Processing 1 of ',num2str(N),' architectures'],...
        'Name','Architectural Evaluation');
tic;
%
for i=1:N
    tic;
    filename=strcat(base,num2str(i),file_extension);
    %check if this file exists
    if(exist(filename,'file')==0)
        message=strcat('File ',filename,' does not exist');
        error(message);
    else
        %file exists..
        disp(['Processing architecture ',num2str(i)]);
        %[numeric,text]=xlsread(filename,sheet);
        q=importdata(filename);
        numeric=q.data;
        A=unitize(numeric);
        % q=importdata(filename);
        %A=q.data;
        arch_array{i}=A;
        if(~isconnected(A)&&(size(A,1)==size(A,2)))
            disp(['Architecture ',num2str(i),' is disconnected']);
            complexity(i)=-100;
            num_connections(i)=-1;
            num_components(i)=-1;
        else
            %architecture is connected...
            num_components(i)=size(A,1);
            num_connections(i)=sum(sum(A));
            complexity(i)=num_components(i)+ (num_connections(i)*sum(svd(A)))/(num_components(i));
        end
    end
    %progress monitoring..
    t=toc;
    t2=[t2;t];
    time=mean(t2);
    remain=time*(N-i);
    hour=floor(remain/3600);
    minutes=floor(remain/60)-hour*60;
    sec=round(mod(remain,60));
    waitbar((i)/(N),h,['Estimated Time Remaining: ',num2str(hour),'h ',...
        num2str(minutes),'m ',num2str(sec),'s'])
    %
end
close(h);
%post-processing steps...
ind=find(complexity>0); %connected architectures...
arch=arch(ind');
complexity=complexity(ind');
num_connections=num_connections(ind');
num_components=num_components(ind');
arch_array=arch_array{ind'};
%find invalid architectures...
invalid_arch=setdiff([1:N],ind);
if(~isempty(invalid_arch))
    disp('Following architectures are invalid');
    disp('==================================================');
    disp(num2str(invalid_arch));
end
%
%plotting...
figure();
% subplot(1,3,1);
% plot(arch,num_components,'bo-');
% xlabel('Architecture #');
% ylabel('Number of Components');
% hold on
% subplot(1,3,2);
% plot(arch,num_connections,'bo-');
% xlabel('Architecture #');
% ylabel('Number of Connections');
% hold on
% subplot(1,3,3);
plot(arch,complexity,'bo-');
xlabel('Architecture #');
ylabel('Complexity');
%
figure();
[complexity_sorted,index]=sort(complexity,'descend');
plot(complexity_sorted,'r*-');
%xlabel('Architecture');
ylabel('Complexity');
title('Structural Complexity of enumerated architectures in descending order');
disp(['Minimum complexity = ',num2str(complexity_sorted(end)),' - architecture No. ',num2str(index(end))]);
disp(['Maximum complexity = ',num2str(complexity_sorted(1)),' - architecture No. ',num2str(index(1))]);
%write out the complexity numbers...
complexity_records = [arch' complexity];
dlmwrite('complexity_numbers_L1.txt',complexity_records,' ');
[y,ind]=sort(complexity_records(:,2),'descend');
complexity_record_sorted=complexity_records(ind,:);
disp(['Structural Complexity metrics generated for ',num2str(length(ind)),' architectures']);
toc;
%clock
%Visualize lowest conplexity architecture..
% filename=strcat(base,num2str(index(end)),file_extension);
% q=importdata(filename);
% A_min_complexity=q.data;
% out_str1=ezread(filename);
% comp1=out_str1.x';
% addtosystempath('/usr/local/bin/');
% X1=graphViz4Matlab('-adjMat',A_min_complexity','-layout',Springlayout,'-nodeLabels',comp1);
% %Visualize lowest conplexity architecture..
% filename=strcat(base,num2str(index(1)),file_extension);
% q=importdata(filename);
% A_max_complexity=q.data;
% out_str2=ezread(filename);
% comp2=out_str2.x';
% X2=graphViz4Matlab('-adjMat',A_max_complexity','-layout',Springlayout,'-nodeLabels',comp2);
%Structural Complexity metric calculation ends here
%
%
%Perform performance calculatione here...
%The set of architectures to be evaluated are indexed in array 'arch'...
disp('Proceed with transfer function calculations ')
input('Press ENTER to continue: ')
%keyboard
disp(['=============================================']);
%architectures;
%clock
%[tf_arch,infeasible_list] = rcl_topo2_tf(rcltopology);
%clock
main
%
infeasible_list
feasible_arch=setdiff(arch,infeasible_list);
%
tf_feasible_arch=tf_arch{feasible_arch};
%
unique_list = [5 11 19 25 30 38 44 46 57 67 70 73 91 101 125 141]
a=importdata('complexity_numbers_L1.txt');
complexities_unique_high_pass_filters = a(unique_list,1:2)
dlmwrite('complexity_numbers_L1_unique_high_pass_filters.txt',complexity_records,' ');
%
disp('Proceed with heat transfer calculations (Arch #73) ')
input('Press ENTER to continue: ')
% Hest transfer calculation goes here...
disp(['============================================']);
tic;Thermal_Script_Yu;toc
%Performance calculation ends here...