%% Reorganize the preconditioning results 

load 'cgikl-d-4-p-5.mat'

%%
set(0,'defaultlinelinewidth',1.2);
set(0,'defaultaxeslinewidth',0.7);
set(0,'defaultaxesfontsize',12);
TufteRed = [0.8 0 0];




%% Convert into a labeled linear form and plot
clf; hold on;
clear presults;
hs = [];
ptext = {};

r = all_results.nopre;
pr.type = 'no preconditioning';
pr.resvec = r.resvec;
pr.time = r.dt;
pr.setup = 0;
pr.hist = r.hist;
presults(1) = pr;

h = semilogy(pr.resvec,'k--');
hs(end+1) = h;
ptext{end+1} = pr.type;

%
%

r = all_results.maxeig_exact(end);
pr.type = 'largest eigenvalue';
pr.resvec = r.resvec;
pr.time = r.dt;
pr.setup = 0;
pr.hist = r.hist;
presults(end+1) = pr;

h = semilogy(pr.resvec,'k-.');
hs(end+1) = h;
ptext{end+1} = pr.type;

r = all_results.mineig_fmincon(end);
pr.type = 'smallest eigenvalue';
pr.resvec = r.resvec;
pr.time = r.dt;
pr.setup = 0;
pr.hist = r.hist;
presults(end+1) = pr;

h = semilogy(pr.resvec,'k-');

hs(end+1) = h;
ptext{end+1} = pr.type;

for i=1:length(all_results.random)
    r = all_results.random(i);
    pr.type = 'random';
    pr.resvec = r.resvec;
    pr.time = r.dt;
    pr.setup = 0;
    pr.hist = r.hist;
    presults(end+1) = pr;
    h = semilogy(pr.resvec,'k--','LineWidth',0.8,'Color',[100 149 237]/255);
end

hs(end+1) = h;
ptext{end+1} = pr.type;

%replot smallest eigenvalue to get it correctly overlaid
r = all_results.mineig_fmincon(end);
pr.type = 'smallest eigenvalue';
pr.resvec = r.resvec;
pr.time = r.dt;
pr.setup = 0;
pr.hist = r.hist;
presults(end+1) = pr;

h = semilogy(pr.resvec,'k-');




r = all_results.midpoint;
pr.type = 'midpoint';
pr.resvec = r.resvec;
pr.time = r.dt;
pr.setup = 0;
pr.hist = r.hist;
presults(end+1) = pr;

h = semilogy(pr.resvec,'r-','Color',TufteRed);
hs(end+1) = h;
ptext{end+1} = pr.type;


r = all_results.mean(end);
pr.type = 'mean';
pr.resvec = r.resvec;
pr.time = r.dt;
pr.setup = 0;
pr.hist = r.hist;
presults(end+1) = pr;

h = semilogy(pr.resvec,'b--');
hs(end+1) = h;
ptext{end+1} = pr.type;


lh = legend(hs,ptext{:},'Location','E');
legend boxoff;

set(gca,'YScale','log');
maxlim = 350;
xlim([0,maxlim]);
th = text(maxlim,1.5*presults(1).resvec(maxlim),...
    sprintf('Converged at\niteration %i\n',...
        length(presults(1).resvec)));
set(th,'HorizontalAlignment','right');    

th = text(maxlim,0.95*presults(2).resvec(maxlim),...
    sprintf('Converged at\niteration %i\n',...
        length(presults(2).resvec)));
set(th,'HorizontalAlignment','right');    
set(th,'VerticalAlignment','top');
xlabel('Iteration');
ylabel('Residual');

% You may have to play around with sizing to get the sizes 
% of the final figure perfect.
set(gcf,'Position',[   808   812   752   523]); % copied from my fig
% nudge the position of the legend
lpos = get(lh,'Position');
lpos(2)=lpos(2)+0.15;
set(lh,'position',lpos);

%%
set(gcf,'Color','none'); set(gcf,'InvertHardCopy','off');
set(gca,'Color','none'); 
print('precond-all.eps','-depsc2');
!evince precond-all.eps
