%% supp
nn = nanmedian(nnWithinGenome.secondOrder.corrs(:, 1:2), 2);
figure; 
subplot(1,2,1);
dscatter(expP, nn);
xlabel('dataset control'); ylabel('nearst neighbor');
axis square; box on; grid on;
set(gca, 'fontsize', fs);
r = corr(expP, nn, 'rows', 'pairwise');
text(0.3, 0.95, ['R = ', num2str(round(r, 2))], 'fontsize', fs);

subplot(1,2,2);
dscatter(nn, obs_all(:, 1)); hold on;
colormap(cm2);
plot([.5 1], [.5 1], 'k');
axis([.5 1 -1 1]);
axis square; box on; grid on;
xlabel('Nearest Neighbor');
ylabel('between species');
set(gca, 'fontsize', fs);
set(gcf, 'color', 'w', 'position', [520   227   865   571]);
th = 0.2;
x = nn;
y = obs_all(:, 1);
idx1 = find(y > th);
idx2 = find(y < th);
x1 = x(idx1);
y1 = y(idx1);
[r, p] = corr(x1, y1, 'rows', 'pairwise')

x2 = x(idx2);
y2 = y(idx2);
[r, p] = corr(x2, y2, 'rows', 'pairwise')

% p1 = linortfit2(x1,y1);
% xs = [.5 1];
% f1 = polyval(p1, xs);
% plot(xs, f1, 'r')
% 
% p2 = linortfit2(x2,y2);
% xs = [.5 1];
% f2 = polyval(p2, xs);
% plot(xs, f2, 'b')

% legend({'genes', 'x=y', 'fit for y>0.2', 'fit for y<0.2'});
%% co-expression vs. expression level / flexibility / dynamic range

medians = nan(6701, 4);
flex = nan(6701, 4);
drange = nan(6701, 4);
for i = 1:4
    currEntry = ['WCD', gb{i}];
    medians(:, i) = nanmedian(dataS.(currEntry), 2);
    flex(:, i) = mad(dataS.(currEntry),[], 2);
    p10 = prctile(dataS.(currEntry), 10, 2);
    p90 = prctile(dataS.(currEntry), 90, 2);
    drange(:, i) = p90 - p10;
end

toPlot = [medians(:, 1),drange(:, 1)];
toPlot = toPlot(intint, :);
xlabels = {'median expression level', 'dynamic range'};
figure;
for i = 1:2
    subplot(2,2,i);
    dscatter(toPlot(:, i), exp_all(:, 1));
    xlabel(xlabels{i});
    ylabel('Rc dataset control');
    axis square; grid on; box on; set(gca, 'fontsize', fs);
    r = corr(toPlot(:, i), exp_all(:, 1))
end

for i = 1:2
    subplot(2,2,i+2);
    dscatter(toPlot(:, i), obs_all(:, 1));
    xlabel(xlabels{i});
    ylabel('Rc between species');
    axis square; grid on; box on; set(gca, 'fontsize', fs);
    r = corr(toPlot(:, i), obs_all(:, 1))
end
colormap(cm);
set(gcf, 'color', 'w');