% This script takes data from stored .mat files and turns it into tables, 
% thus the .mat file need to be available in 'folder' before this 
% script is ran. The tables are written to files using writetable()
% The generated tables are used in pgfplot commands through the thesis.
% If anything in the simulation changes, this program just has to be ran
% once to update all plots in the thesis.
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
folder ='C:\Users\Vegard\Dropbox\Master\latex\fig\table\'; 
d = 'delimiter';
% Generate 24 hour data points. The date is just there to comply with
% ..pgfplot standards.(requires full date) The hour is all that matters.
twentyfour = [];      % 24-hour array. To contain strings, starting at 4.00
for i=4:27
    if i >9   % strings contained in array must have same length. 
        if i >24              % if above 24 we want to start at 01.00 again
            twentyfour=[twentyfour;['{2009-08-19 0',int2str(i-24),':00}']];
        else
            twentyfour=[twentyfour;['{2009-08-18 ',int2str(i)    ,':00}']];
        end
    elseif i<=9 % adding an additional 0 to keep strings same length.
        twentyfour =   [twentyfour;['{2009-08-18 0',int2str(i)   ,':00}']];
    end
end

%Average demand and price table
av.price  = csvread('average.csv',0,1,[0,1,23,1]);             % P, EUR/MWh
av.demand = csvread('average.csv',0,0,[0,0,23,0]);         % q_hw, dm^3/min
historicav = table(twentyfour,av.demand,av.price,...
                    'VariableNames',{'Time' 'Demand' 'Price'});
writetable(historicav,fullfile(folder,'average.dat'),d,'\t')


%Current demand and price table
test=load('langprofil.mat');
a = test.testlong;
currentdem = table(a.time' +0.0167,a.flow,a.price,...     % q_out, dm^3/min
                   'VariableNames',{'Time' 'Demand' 'Price'});
writetable(currentdem,fullfile(folder,'pricedemand.dat'),d,'\t')

%Price and average price
weekdata = getPriceHour(4,1,4,7);              % get one week of price data
pricecompTbl = table(twentyfour, weekdata(1:24),weekdata(25:48), ...
                  weekdata(49:72),weekdata(73:96),weekdata(97:120), ...
                  weekdata(121:144),weekdata(145:168), av.price);
writetable(pricecompTbl,fullfile(folder,'pricecomp.dat'),d,'\t')

%Back-off
p='C:\Users\Vegard\Dropbox\Master\MATLAB\_TJ_data_V200_m123_BO975310.mat';
bo=load(p,'Tresult','Jresult','boList');
boTbl  = table(bo.boList, bo.Tresult(:,1),bo.Tresult(:,2),...
    bo.Tresult(:,3),bo.Jresult(:,1),bo.Jresult(:,2),bo.Jresult(:,3),...
    'VariableNames',...
             {'Backoff' 'Tmode1' 'Tmode2' 'Tmode3' 'Jmode1' ...
             'Jmode2' 'Jmode3' });
writetable(boTbl,fullfile(folder,'bo.dat'),d,'\t')



%Simple control rules
simplec=load('C:\Users\Vegard\Dropbox\Master\MATLAB\cstructuresBO3.mat',...
             'rmat');
htable  = (1:numberofelements(simplec.rmat(:,1)) );
simplecTbl = table(htable', simplec.rmat(:,3), simplec.rmat(:,4),...
			 simplec.rmat(:,1),simplec.rmat(:,2),'VariableNames',...
             {'Case' 'startime' 'length' 'T_violation' 'J_end' });
writetable(simplecTbl,fullfile(folder,'simplec.dat'),d,'\t')

%Just the simple control rules with s=1
newtable =[];
for i=1:numberofelements(htable)
    %temp =[]
    if simplec.rmat(i,3) == 1
        newtable=[newtable;simplec.rmat(i,1:4)];
    end
end
simplec2Tbl = table(newtable(:,1), newtable(:,2),...
			 newtable(:,3), newtable(:,4),'VariableNames',...
             {'T_violation' 'J_end' 'startime' 'length'  });
writetable(simplec2Tbl,fullfile(folder,'simplec2.dat'),d,'\t')


%Sizing
path='C:\Users\Vegard\Dropbox\Master\MATLAB\_TJ_data_V60-800_m123_BO3';
sizeBO=load(path,'Tresult','Jresult','vlist');
addCostTbl =table(sizeBO.vlist(1:6), sizeBO.Jresult(1:6,1)-...
            sizeBO.Jresult(1:6,2),sizeBO.Jresult(1:6,1)-...
            sizeBO.Jresult(1:6,3),'VariableNames',...
             {'Volume','addCostOpt','addCostSim'})
writetable(addCostTbl,fullfile(folder,'addCost.dat'),d,'\t')
%no deldta
sizeCostTbl =table(sizeBO.vlist(1:6), sizeBO.Jresult(1:6,1),...
            sizeBO.Jresult(1:6,2),sizeBO.Jresult(1:6,3),'VariableNames',...
             {'Volume','Jb','Jo','Jt'})
writetable(sizeCostTbl,fullfile(folder,'sizeCost.dat'),d,'\t')


addTviolTbl = table(sizeBO.vlist(1:6), sizeBO.Tresult(1:6,1),...
          sizeBO.Tresult(1:6,2),sizeBO.Tresult(1:6,3),'VariableNames',...
              {'Volume','TviolBase','TviolOpt','TviolSim'})
writetable(addTviolTbl,fullfile(folder,'addTviol.dat'),d,'\t')

%Effect of BO on sizing
path2='C:\Users\Vegard\Dropbox\Master\MATLAB\_TJ_data_V60-800_m123';        
size=load(path2,'Tresult','Jresult','vlist');
%Add statement here checking if the two incoming volume lists are  the same
if sizeBO.vlist ~= size.vlist, raise.error('The vlists nonidentical!'); end
% create the table for temp-violation with and without BO
BuTempTbl =  table(size.vlist(1:6), sizeBO.Tresult(1:6,2)-...
             sizeBO.Tresult(1:6,1),...
             size.Tresult(1:6,2)-size.Tresult(1:6,1),...
             sizeBO.Tresult(1:6,2)-sizeBO.Tresult(1:6,1)-...
             (size.Tresult(1:6,2)-size.Tresult(1:6,1)),...
             sizeBO.Tresult(1:6,3)-sizeBO.Tresult(1:6,1),...
             size.Tresult(1:6,3)-size.Tresult(1:6,1),...
             sizeBO.Tresult(1:6,3)-sizeBO.Tresult(1:6,1)-...
             (size.Tresult(1:6,3)-size.Tresult(1:6,1)),'VariableNames',...
             {'Volume','addTempOptBO','addTempOpt','deltaTempOptBO',...
             'addTempSimBO','addTempSim','deltaTempSimBO'})
% create the table for cost with and without BO
BuCostTbl =  table(size.vlist(1:6), sizeBO.Jresult(1:6,1)-...
             sizeBO.Jresult(1:6,2),...
             size.Jresult(1:6,1)-size.Jresult(1:6,2),...
             sizeBO.Jresult(1:6,1)-sizeBO.Jresult(1:6,2)-...
             (size.Jresult(1:6,1)-size.Jresult(1:6,2)),...
             sizeBO.Jresult(1:6,1)-sizeBO.Jresult(1:6,3),...
             size.Jresult(1:6,1)-size.Jresult(1:6,3),...
             sizeBO.Jresult(1:6,1)-sizeBO.Jresult(1:6,3)-...
             (size.Jresult(1:6,1)-size.Jresult(1:6,3)),'VariableNames',...
             {'Volume','addCostOptBO','addCostOpt','deltaCostOptBO',...
             'addCostSimBO','addCostSim','deltaCostSimBO'})
         
writetable(BuTempTbl,fullfile(folder,'TviolBO.dat'),d,'\t')
writetable(BuCostTbl,fullfile(folder,'CostBO.dat'),d,'\t')



%% Making 3 day plots

std = load('C:\Users\Vegard\Dropbox\Master\MATLAB\_datasetsV200.mat');
length=51552+288*2; %3 days in simulation points (32 steps? (96)*3)
step = 288%96%288

baseTbl = table(std.ptime_base(1:step:length),... 
           std.y_base(1:step:length,2),...
           std.sp_base(1:step:length,2),std.y_base(1:step:length,1),...
           std.sp_base(1:step:length,1),std.y_base(1:step:length,3),...
           std.d_base(1:step:length,4),std.d_base(1:step:length,1),...
           std.u_base(1:step:length,1),std.u_base(1:step:length,2),...
           'VariableNames',{'time' 'T' 'T_s' 'V' 'V_s' 'J_tot' 'price'...
               'q_hw' 'Q' 'q_in'});
writetable(baseTbl,fullfile(folder,'base3.dat'),d,'\t')


%optim case
optimTbl = table(std.ptime_optim(1:step:length),... 
           std.y_optim(1:step:length,2),...
           std.sp_optim(1:step:length,2),std.y_optim(1:step:length,1),...
           std.sp_optim(1:step:length,1),std.d_optim(1:step:length,4),...
           'VariableNames',{'time' 'T' 'T_s' 'V' 'V_s' 'price'});
writetable(optimTbl,fullfile(folder,'optim3.dat'),d,'\t')

%two phase case
twophaseTbl = table(std.ptime_sim(1:step:length),... 
           std.y_sim(1:step:length,2),...
           std.sp_sim(1:step:length,2),std.y_sim(1:step:length,1),...
           std.sp_sim(1:step:length,1),std.d_sim(1:step:length,4),...
           'VariableNames',{'time' 'T' 'T_s' 'V' 'V_s' 'price'});
writetable(twophaseTbl,fullfile(folder,'twophase3.dat'),d,'\t');


%known demand
%plotting the results of known and average demand optimization
kno = load('C:\Users\Vegard\Dropbox\Master\MATLAB\_pdatasetsV200.mat');
knownTbl = table(kno.ptime_optim2(1:step:length),... 
            kno.sp_optim2(1:step:length,2),...
             std.sp_optim(1:step:length,2),std.d_optim(1:step:length,4),...
             std.d_optim(1:step:length,1),'VariableNames',...
             {'time' 'T_sk' 'T_sa' 'price' 'q_hw'});
writetable(knownTbl,fullfile(folder,'stdVsknown3.dat'),d,'\t');

%plotting average hourly demand for three days
time2=[4:1:75]';
averagedemand =[av.demand; av.demand; av.demand];
%plotting known hourly demand for three days
actualdemand = [];
for i=1:72
    temrep = a.flow( (60*(i-1)+1):(60*i) );
    actualdemand=[actualdemand;sum(a.flow( (60*(i-1)+1):(60*i) ))/60];
end
knownTbl2 = table(time2,averagedemand, actualdemand, 'VariableNames',...
             {'time2' 'h_avdemand' 'h_actualdemand'});

writetable(knownTbl2,fullfile(folder,'stdVsknown3b.dat'),d,'\t')

step=2880
%% Plotting total cost and table
%plotting cost functions for 30 days
lenthirty = 515521;
CostyTbl = table(std.ptime_base(1:step:lenthirty)/24,... 
           std.y_base(1:step:lenthirty,3),...
           std.y_optim(1:step:lenthirty,3),...
           std.y_sim(1:step:lenthirty,3),...
           'VariableNames',{'time' 'J_base' 'J_optim' 'J_sim'})
writetable(CostyTbl,fullfile(folder,'Jplot.dat'),d,'\t');
%plotting cost at the end of simulation
Var =['{$ J $}';'{$t_v$}'];
Jbase= [sizeBO.Jresult(4,1);sizeBO.Tresult(4,1)];
Joptim= [sizeBO.Jresult(4,2);sizeBO.Tresult(4,2)];
Jsim=[sizeBO.Jresult(4,3);sizeBO.Tresult(4,3)];
CostxTbl = table(Var,Jbase,Joptim,Jsim,...
           'VariableNames',{'Objective' 'J_base' 'J_optim' 'J_sim'})
writetable(CostxTbl,fullfile(folder,'Jtab.dat'),d,'\t')


% switch block
step=5
pathswitch='C:\Users\Vegard\Dropbox\Master\MATLAB\switchplot';        
iz=load(pathswitch);
swstart=1;
switchTbl=table(iz.ptime_base(swstart:step:end)-iz.ptime_base(swstart),...
         iz.y_base(swstart:step:end,1),iz.sp_base(swstart:step:end,1),...
         iz.y_base(swstart:step:end,2),iz.sp_base(swstart:step:end,2),...
         'VariableNames',{'time' 'V' 'Vs' 'T' 'Ts'})
writetable(switchTbl,fullfile(folder,'Switch.dat'),d,'\t')