%==============================================================================
%    clust_composition.m
%    Copyright (C) 2007  Amoolya H. Singh, singh@embl.de
%
%    This program 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.
%
%    This program 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 this program.  If not, see <http://www.gnu.org/licenses/>.
%===============================================================================
function S = clust_composition(T, perm, C, descr) 
%------------------------------------------------------------------------------
%
% S = clust_composition(T, perm, C, descr) calculates the fractional
% composition of each cluster according to the given categories
%
% Input: 
%   T, grouping vector
%   perm, permutation vector
%         (Both these are returned by 'dendrogram' which clusters any
%         data matrix, in our case the phylo profile matrix)
%   C, grouping vector from either functional ontology (genes) or
%      phenotypic scoreing (species)
%   descr, affiliated strings describing C in words (genes) or
%          bitstrings (species)
% Output:
%   S, which describes for each cluster (columns), the fractional contribution
%   of each category (rows)
%
%------------------------------------------------------------------------------

nclusters = max(perm);
ncategories = length(descr);

S = zeros(ncategories,nclusters);

for i=1:nclusters
  clust = C(find(T==perm(i)));
  freqs = histc(clust,1:ncategories);
  S(:,i) = freqs/sum(freqs);
end

% remove zero entries
ind = find(sum(S')==0);
descr(ind) = [];
S(ind,:) = [];
ncategories = length(descr);

% visualize
figure,bar(S','stacked');
axis tight
legend(descr);
set(gca,'XTickLabel',perm)
xlabel('Module Number')
ylabel('Fraction')
%%colormap(colormat)
colormap(jet)
caxis([1 ncategories])

