function retW = CalcOptW(inEta,inFamily,inLink)
%function retW = CalcOptW(inEta,inFamily,inLink)
% 
% Calculate the optimal weight matrix for GLM. Note that
%                b'(theta)=g^{-1}(eta).
%
% Input:
%   inEta: eta;
%   inFamily: family of the distribution;
%   inLink: link function g().
%
% Output:
%   retW: nx1 weight vector for weight matrix W.
%
% Dabao Zhang    May 23, 2013
%
% Revised by:
%
% Copyright (c) 2013 by Dabao Zhang.

error(nargchk(3, 3, nargin));

% kappa = b'(theta) &  var(Y) is proportional to b''(theta)
kappa = ginv(inEta,inLink);
switch inFamily
    case 'normal'
        % b'(theta)=2*theta
        vy = ones(size(kappa,1),1);
    case 'binomial'
        % b'(theta)=1/(1+exp(-theta))
        vy = kappa.*(1-kappa);
    case 'poisson'
        % b'(theta)=exp(theta)
        vy = kappa;
    case 'gamma'
        % b'(theta)=1/theta
        vy = kappa.^2;
    case 'inverse gaussian'
        % b'(theta)=theta^2
        vy = sqrt(kappa);
    case 'quasi'
        error('  gPOCRE: The family is not supported...');
    otherwise
        error('  gPOCRE: The family is not supported...');
end

% W = {\Delta g^{-1}(eta)}^2 / b''(theta) (normalized)
retW = dginv(inEta,inLink);
retW = retW.*(retW./vy);
retW = retW./sum(retW);
