% Delivered to the U.S. 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.

% Authors:  Fernando Rodriguez                      John Finn
%           Sr Engineer/Scientist                   Contractor (Summer Intern 2011)
%           Power Electronics Systems               Embedded Systems & Networks
%           United Technologies Research Center     United Technologies Research Center
%           411 Silver Lane                         411 Silver Lane
%           East Hartford,CT 06108                  East Hartford,CT 06108
%           rodrigf@utrc.utc.com                    ccfinnje@utrc.utc.com
%           tel: (860) 610-7102                     tel: +1 860-610-7696
%%
% EPSdata_process.m
% Separates subsystems before performing Load Flow analysis
function [ALL_linedata, ALL_busdata, n_min, n_max, a, subs, EPS_Code, Conv_data, n_cd]...
    = EPSdata_process(Source_data, TL_data, SW_data, Load_data, Conv_data, EPS_Code)
%% -------------Create Bus_data and EPSlinedata----------
%EPSdata
EPSlinedata = [SW_data;TL_data];    %SW and TL data
Bus_data=[Source_data;Load_data];   %Source and Load data
EPS_Code=EPS_Code';                 % Transpose EPS_Code matrix

comp = length(EPSlinedata(:,1));    %number of EPSlinedata components
code =     EPSlinedata(:,2);        %EPS_Code of EPSlinedata rows
nl   =     EPSlinedata(:,3);        %Left bus no.
nr   =     EPSlinedata(:,4);        %Right bus no.
Z    =     EPSlinedata(:,5);        %Impedance of component
subs = max(code);     % number of subsystems
nbus = max([nl;nr]);  % number of buses...assumes continous bus indexing (1,2,...,n)
%% ---Remove impaginary part of impedance if comp is in "DC" subsystem---
for i=1:length(EPS_Code(4,:))               %Step thru EPS Codes
    if EPS_Code(4,i) == 1                   %If EPS_code is "DC"
        for ii=1:comp                       %Step thru EPSlinedata
            if code(ii) == EPS_Code(1,i)    %If comp is "DC"
                Z(ii) = real(Z(ii));        %Z=Re{Z}
            end
        end
    end
end
%% -------------------CREATE ALL_linedata-----------------------
% ALL_linedata = [EPS_Code nl nr Z]: start w/ subsystem = 1,2,...,n
% a tracks number of comp+1 in each subsystem  ??????? NEEDS BETTER DEFINITION
% n_max tracks highest bus number per subsystem
% n_min tracks lowest bus number per subsystem
a=ones(subs,1); n_max =zeros(subs,1);  n_min = ones(subs,1)*nbus;  
k = 0;          %index used to create ALL_linedata

% Step thru EPSlinedata and create ALL_lindata starting with subs 1,2,...,n
for i=1:subs
    for ii=1:comp
        if code(ii) == i && Z(ii) ~= 0 %removes SW = 0
            k = k+1; 
            %                   EPS Code      nl       nr      Impedance
            ALL_linedata(k,:) = [code(ii)   nl(ii)    nr(ii)     Z(ii)];
            n_max(i) = max([n_max(i) nl(ii) nr(ii)]);
            n_min(i) = min([n_min(i) nl(ii) nr(ii)]);
            a(i) = a(i)+1;  % comp count+1 per subsystem (used in EPS_Load_Flow.m)
        end
    end
end

%Step thru Bus_data, check n_min & n_max for lower/higher bus #
for u1=1:length(EPS_Code(1,:))  %for every EPS_Code
    for u2=1:length(Bus_data(:,1))  %for every Bus_Data entry
        if Bus_data(u2,3)==u1 && n_min(u1) > Bus_data(u2,1) 
            n_min(u1) = Bus_data(u2,1); %update n_min if lower bus# exists
        elseif Bus_data(u2,3)==u1 && n_max(u1) < Bus_data(u2,1)
            n_min(u1) = Bus_data(u2,1); %update n_max if higher bus# exists
        end
    end
end
        
% Re-Index buses so each subsystem buses start at 1
clear code nl nr %Variables are re-defined becase SW's =0 are were removed
code =   ALL_linedata(:,1);
nl   =   ALL_linedata(:,2);
nr   =   ALL_linedata(:,3);
for i=1:subs
    for ii=1:k      % k is length of ALL_linedata
        if code(ii) == i
            ALL_linedata(ii,2:3) = [nl(ii) nr(ii)]-[1 1]*(n_min(i)-1);
        end
    end
end

%% -------------------CREATE ALL_busdata-----------------------
%               Bus Bus  Vltg  Angle  -----Load-----   -Generator- 
%               No  code Mag   Degree   watt    kvar    watt     var
%ALL_busdata= [ #    #   Vm    Angle     Pd      Qd      Pg      Qg]
n = n_max - n_min + 1;          %number of buses for each code
ALL_busdata = zeros(sum(n),8);  %initialize ALL_busdata
ALL_busdata(:,1) = [1:sum(n)];  %Number buse ndx comlumn [1:sum(n)]

% Find source and load buses in Bus_data
for i=1:length(Bus_data(:,1))
    bus_code = Bus_data(i,2);
    if bus_code == 1        %if source bus
        ii=Bus_data(i,1);
        ALL_busdata(ii,2) = 1; %set BusCode = 1
    elseif bus_code == 0;   %if load bus
        ii=Bus_data(i,1);
        ALL_busdata(ii,5:6)=Bus_data(i,4:5); %update Pd & Qd
    end
end

% Find Converter "slack" and "load" buses in Bus_data
n_cd = length(Conv_data(:,1));    % row length of Conv_data
if n_cd == 1 && Conv_data(1,1) ==0
    n_cd=0; %Incase no converters are present
end 
for i=1:n_cd
    ii=Conv_data(i,3);
    ALL_busdata(ii,2) = 1;
end
end