clear all
%% MATLAB script to write csv file from Local solution data
%   W. A. Bukhsh, Nov. 14, 2012 
%%   References:
%   [1] W. A. Bukhsh, Andreas Grothey, Ken McKinnon, Paul trodden, "Local Solutions of Optimal Power Flow Problem"
%       submitted to IEEE Transactions on Power Systems, 2013
%   [2] W. A. Bukhsh, Andreas Grothey, Ken McKinnon, Paul trodden, "Local Solutions of Optimal Power Flow Problem"
%       Technical Report ERGO, 2011


%% Select mat file
%file='WB2data_2solns.mat';
%file='WB3data_2solns.mat';
%file='WB5data_2solns.mat';
%file ='case9data_4solns.mat';
%file = 'case22loopdata_2solns.mat';
%file = 'case39data_16solns_linear.mat';
%file = 'case39data_2solns_quadratic.mat';
%file='case118data_3solns.mat';
%file='case300data_7solns.mat';
file='LMBM3.mat';
%%
load(file);
fid=fopen([file(1:end-4) '.csv'],'w');

nloc=numel(ACsol);    %no of local solutions
nb=numel(ACsol(1).v); %no of buses
ng=numel(ACsol(1).pG);%no of generators
nL=size(params.A,1);  %no of lines

for q=1:nloc
    fprintf(fid,'Local Solution %d\n',q);
    fprintf(fid,'Objective Value= %4.8f\n',sum(params.c2(:,2)'.*((ACsol(q).pG*100).^2)+params.c1(:,2)'.*((ACsol(q).pG*100))+params.c0(:,2)'));
    
    
    %headers
    fprintf(fid,'Bus,');
    fprintf(fid,'Voltage,');
    fprintf(fid,'Angle(deg)\n');

    for p=1:nb
        fprintf(fid,'%d,',p);
        fprintf(fid,'%4.8f,',ACsol(q).v(p));
        fprintf(fid,'%4.8f\n',ACsol(q).delta(p)*180/pi);
    end

   
    %headers
    fprintf(fid,'Generation\n');
    fprintf(fid,'Bus,');
    fprintf(fid,'P(MW),');
    fprintf(fid,'Q(MVars)\n');

    for p=1:ng
        fprintf(fid,'%d,',sets.Gbs(p,1));
        fprintf(fid,'%4.8f,',ACsol(q).pG(p)*100);
        fprintf(fid,'%4.8f\n',ACsol(q).qG(p)*100);
    end
    
    %headers
    fprintf(fid,'Line Flows\n',p);
    fprintf(fid,'from,');
    fprintf(fid,'to,');
    fprintf(fid,'P(MW),');
    fprintf(fid,'Q(MW),');
    fprintf(fid,'Line Loss(MW)\n');
    
    
    
    for p=1:nL
        fprintf(fid,'%d,',params.A(p,2));
        fprintf(fid,'%d,',params.A(p,3));
        fprintf(fid,'%4.8f,',ACsol(q).pLfrom(p)*100);
        fprintf(fid,'%4.8f,',ACsol(q).qLfrom(p)*100);
        fprintf(fid,'%4.8f,',(ACsol(q).pLfrom(p)+ACsol(q).pLto(p))*100);
    end
    fprintf(fid,'\n\n');
end
  

    