function [hme] = hmeInitLR(hme,x,y)
% [hme] = hmeInitLR(hme,x,y)
%
% Initialize an HME model by fitting the logistic functions in the
% gating network and expert nodes in a top-down manner.  This only
% makes sense if the branching factor of the tree is equal to the
% number of classes.
%
%	hme	HME model to initialize.
%	x	dxn matrix of samples
%	y	kxn matrix of class assignments
% 
% See also hmeCreate, hmeInitRand.
%
% David Martin <dmartin@eecs.berkeley.edu>
% May 2002

% Copyright (C) 2002 David R. Martin <dmartin@eecs.berkeley.edu>
%
% 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 2 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, write to the Free Software
% Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA
% 02111-1307, USA, or see http://www.gnu.org/copyleft/gpl.html.

[d,n] = size(x);
hme = initTree(hme,x,y,ones(1,n));

function [hme] = initTree(hme,x,y,w)
  
  if hme.leaf,	% expert

    hme.param = logistK(x,y,w);

  else	% gating node
    
    [k,n] = size(y);
    [d,b] = size(hme.param);
    if b == k,
      [hme.param,post] = logistK(x,y,w);
      for i = 1:length(hme.children),
        wi = w .* post(i,:);
        hme.children{i} = initTree(hme.children{i},x,y,wi);
      end
    else
      warning(sprintf('Can''t initialize gating node since (k=%d) != (b=%d).',k,b));
    end
    
  end
  
