% This function uses the struct created when using the vdpgm toolbox,
% which automatically determines the number of clusters. Each cluster is 
% assigned a label based on the most common label of its constituent
% samples. Thus if there are k clusters then the output of this function 
% will be a kx1 vector of each clusters' samples' most common label. Note 
% that multiple clusters can share the same labels.

function [cluster_labels] = gen_cluster_labels(dpm_results, train_labels)
    %Find the number of clusters from dpm_results. If the algorithm used is
    %AVDPM, then the number of clusters is based on K-1 instead of k. This
    %discrepancy is a from the vdpgm code (See readme)
    if isequal(dpm_results.algorithm, 'vdp')
        k = dpm_results.K - 1;  
    else
        k = dpm_results.K;
    end

    % Determine the cluster each sample comes from by choosing the maximum
    % posterior for each sample
    [~,cluster_assignment]=max(dpm_results.q_of_z,[],2);
    
    %cluster_labels=zeros(length(unique(cluster_assignment)),1);
    cluster_labels=zeros(k,1);
    
    % Use the mode of each cluster's samples to determine the cluster's label
    for j = 1:max(cluster_assignment)
        ind = find(cluster_assignment==j);
        if ~isempty(ind)
            cluster_labels(j) = mode(train_labels(ind));
        else
            cluster_labels(j) = 0;
        end
    end
end