% Automatically exclude false-positive subvolumes by cc thresholding.
% Adapted from procesing script.

% set index
idx = 1;

% get table
t = dread('refined_table_ref_001_ite_0003.tbl');

% fit gaussian mixture model (GMM) to cc distribution
gmdist  = fitgmdist(t(:,10), 2);
gmsigma = gmdist.Sigma;
gmmu    = gmdist.mu;

% define theshold at minimum between gaussians plus constant
x      = 0:0.001:0.5;
TF     = islocalmin(pdf(gmdist, x'));
thresh = x(TF)'+0.01;


% plot fit
figure;
hold on;
histogram(t(:,10), 'Normalization', 'pdf', 'EdgeColor', 'none')
plot(x, pdf(gmdist, x'),'linewidth',2)
xline(thresh,'linewidth',2)
xlim([0 0.5])
legend('CC distribution','GMM fit','Threshold')
%title(['Stack: ' stackName{idx}])
xlabel('CC')
ylabel('Occurencies')
set(gca,'Fontsize',12);

% save fit
ax = gca;
exportgraphics(ax,'table_plot_fit.tif','Resolution',300)


% visualize excluded particles 1
figure;
hold on
h = dpktbl.plots.sketch(t(t(:,10)>thresh,:),'haxis',gca());
h.centerSettings.colorFill = 'b';
h.xlength.value = 0; h.ylength.value = 0; h.zlength.value = 0;
h.centerSettings.markersize.value = 4;
h = dpktbl.plots.sketch(t(t(:,10)<thresh,:),'haxis',gca());
h.centerSettings.colorFill = 'r';
h.centerSettings.markersize.value = 4;
h.xlength.value = 0; h.ylength.value = 0; h.zlength.value = 0;
xlim([100 1200])
ylim([100   1000])
zlim([1900 2800])
view(0,45)

% save plot
ax = gca;
exportgraphics(ax,'table_plot_excluded_1.tif','Resolution',300)


% visualize excluded particles 2
figure;
hold on
h = dpktbl.plots.sketch(t(t(:,10)>thresh,:),'haxis',gca());
h.centerSettings.colorFill = 'b';
h.xlength.value = 0; h.ylength.value = 0; h.zlength.value = 0;
h.centerSettings.markersize.value = 4;
h = dpktbl.plots.sketch(t(t(:,10)<thresh,:),'haxis',gca());
h.centerSettings.colorFill = 'r';
h.centerSettings.markersize.value = 4;
h.xlength.value = 0; h.ylength.value = 0; h.zlength.value = 0;
xlim([2860 3600])
ylim([850   1580])
zlim([1800 2200])
view(2)

% save plot
ax = gca;
exportgraphics(ax,'table_plot_excluded_2.tif','Resolution',300)


