function gmms = learnVoteDistribution(voteMix)
% Learn auto clust mixture models
%
% Author: Saurabh Singh (saurabhsingh@cmu.edu)

gmms = learnAutoClustMixtureModelsNonPara(voteMix);
end

function gmms = learnAutoClustMixtureModelsNonPara(voteMix)
sigmaLoc = [ ...
  0.1 0 0 0; ...
  0 0.1 0 0; ...
  0 0 0.1 0; ...
  0 0 0 0.1; ...
];
sigmaLoc = sigmaLoc * 4;

gmms = cell(1, length(voteMix));
nonEmptyInd = getNonEmptyInd(voteMix);
fprintf('Learning GMM ... ');
for i = 1 : length(voteMix)
  vMix = cell2mat(voteMix{i}(:));
  if ~isempty(vMix)
    muLoc = vMix;
    sigLoc = repmat(sigmaLoc, [1, 1, size(muLoc, 1)]);
    proportion = ones(1, size(muLoc, 1)) / size(muLoc, 1);
    gmms{i}.location = gmdistribution(muLoc, sigLoc, proportion);
  else
    muLoc = zeros(size(cell2mat(voteMix{nonEmptyInd})));
    sigLoc = repmat(sigmaLoc * 10000, [1, 1, size(muLoc, 1)]);
    proportion = ones(1, size(muLoc, 1)) / size(muLoc, 1);
    gmms{i}.location = gmdistribution(muLoc, sigLoc, proportion);
  end
end
fprintf('Done\n');
end

function ind = getNonEmptyInd(someCellArray)
for i = 1 : length(someCellArray)
  if ~isempty(someCellArray{i})
    ind = i;
    break;
  end
end
end

function gmms = learnAutoClustMixtureModelsGmm(locMix, scaleMix)
gmms = cell(1, length(locMix));
fprintf('Learning GMM ...');
gmmClust = [2 1];
for i = 1 : length(locMix)
  locGmm = learnGMM(gmmClust, locMix{i});
  gmms{i}.location = doGmmSelection(locGmm);
  scaleGmm = learnGMM(gmmClust, scaleMix{i});
  gmms{i}.scale = doGmmSelection(scaleGmm);
end
fprintf('Done\n');
end

function outGmms = doGmmSelection(inGmms)
lowThresh = 0.3;
if inGmms{1}.PComponents(1) < lowThresh || ...
    inGmms{1}.PComponents(1) > 1 - lowThresh
  outGmms = inGmms{2};
else
  outGmms = inGmms{1};
end
end

