% function [bestSol] = maximizeBESS(sol)
% maximizeBESS computes the between-cluster Error Sum of Squares (bESS) for 
% each clustering solution in 'sol', and returns the solution having
% maximum bESS. For more details on the bESS criterion, refer to 
% "A novel solution to the problem of non-uniqueness of the solution in 
% Hierarchical Clustering" (Cattinelli, Valentini, Paulesu, Borghese).
%
% This file is part of Cluster4MetaAnalysis.
%     Cluster4MetaAnalysis is free software: you can redistribute it 
%     and/or modify it under the terms of the GNU General Public License 
%     as published by the Free Software Foundation, either version 3 of 
%     the License, or (at your option) any later version.
% 
%     Cluster4MetaAnalysis is distributed in the hope that it will be 
%     useful, but WITHOUT ANY WARRANTY; without even the implied warranty 
%     of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
%     GNU General Public License for more details.
% 
%     You should have received a copy of the GNU General Public License
%     along with Cluster4MetaAnalysis.  If not, see
%     <http://www.gnu.org/licenses/>.


function [bestSol] = maximizeBESS(sol, data)

% initializing
grandMean = mean(data);
n = size(sol, 2);
bESS = zeros(n, 3);

% compute bESS for each clustering solution
for i=1:n
    for j=1:size(sol(i).clusterData, 1)
        bESS(i, 1:3) = bESS(i, 1:3) + sol(i).clusterData(j, 7) * ((sol(i).clusterData(j, 1:3) - grandMean).^2);
    end
end

normbESS = zeros(n, 1);
for i=1:n
    normbESS(i) = norm(bESS(i, :));
end

% find maximum bESS and return corresponding solution
[m, idx] = max(normbESS);
disp('Max bESS: ')
m

bestSol = sol(idx);

