clear all
close all
prep_figure

%%
load Rall
clear pars
for icv = 1:5
    [~,idx] = sort(arrayfun(@(x) x.fval(end),R(:,icv)))
    pars((icv-1)*5+(1:5),:) = [R(idx(1:5),icv).par]';
end


%%
figure
clear g
g(1,1) = gramm('x',std(pars),'y',median(pars))
g(1,1).geom_point('alpha',0.2)
g(1,1).set_names('x','log-parameter std','y','median value')

for type = {'VAR'}
    switch(type{1})
        case 'VAR'
            fun = @(y,yp) nanvar(y(:));
            fun2 = @(y,yp) nanmean((y(:)-yp(:)).^2);
            ylabel = 'variance of model predictions';
            ylimits = [0,0.1];
            ig = 1;
    end
    yy = [];
    xx = [];
    color = {};
    group = [];
    idx = 1;
    for mode = {'fit','test'}
        switch(mode{1})
            case 'fit'
                sim = sim_fit;
                data = data_fit;
            case 'test'
                sim = sim_test;
                data = data_test;
        end
        for icl = 1:size(sim,1)
            for idrug = 1:size(sim,2)
                for iconc = 1:size(sim,3)
                    y = nanmedian(sim(icl,idrug,iconc,:,:),5);
                    yp = nanmedian(data(icl,idrug,iconc,:,:),5);
                    
                    yy(idx) = fun(y,yp);
                    xx(idx) = conc(iconc);
                    color{idx} = mode{1};
                    group(idx) = 1;
                    idx = idx + 1;
                    if strcmp(type{1},'VAR')
                        yy(idx) = fun2(y,yp);
                        xx(idx) = conc(iconc);
                        color{idx} = mode{1};
                        group(idx) = 2;
                        idx = idx + 1;
                    end
                end
            end
        end 
    end
    g(2,ig) = gramm('x',log10(xx),'y',yy,'color',color,'group',group)
    g(2,ig).stat_summary('geom','lines')
    g(2,ig).set_names('x','drug concentration [nM]','y',ylabel)
    g(2,ig).axe_property('XTick',linspace(-3,1,5),'YLim',ylimits)
    g(2,ig).no_legend()
end
g(2,2) = gramm()
g.draw()


%%
for ig = 1:2
    set(g(2,ig).facet_axes_handles,'XTickLabel',arrayfun(@(x) ['10^{' num2str(x) '}'],get(g(2,ig).facet_axes_handles,'XTick'),'UniformOutput',false))
end

makeFigure(0,0,2,200,200,'figure_prediction_uncertainty_histogram',true)

function name = getReactionName(parname)
    persistent names ids
    
    if(isempty(names) || isempty(ids))
        load('rnames.mat')
        names = R_name(:,2);
        ids = R_name(:,1);
    end
    
    tok_pre = regexp(parname,'^\{([0-9]*)\|','tokens');
    if(~isempty(tok_pre))
        nameidx = find(strcmp(tok_pre{1},ids));
        prefix = names{nameidx};
    else 
        prefix = 'cell viability';
    end
    
    tok_suff = regexp(parname,'|([\w]*)}$','tokens');
    if(~isempty(tok_suff))
        suffix = tok_suff{1}{1};
    else 
        suffix = 'parname';
    end
    
    name = [prefix ' - ' suffix];
end