% make_W.m
%
% Anthony Kellems, 11/24/07
%
% Builds the W matrix for Bayesian net of Lansner and Ekeborg.
% INPUTS:   patterns = p x n matrix of p patterns of n binary cells
%           kappa    = p x 1 vector of significances of learning events
function W = make_W(patterns,kappa)

[p,n] = size(patterns);

pvec = sum(patterns,1)/p;       % probabilities each cell was on

W = zeros(n,n);

Z = sum(kappa);
cvec = kappa'*patterns;         % c_i vector

Cmat = zeros(n,n);              % c_{ij} matrix
for j = 1:n
    for k = 1:n
        Cmat(j,k) = kappa' * (patterns(:,j).*patterns(:,k));
    end
end

for j = 1:n
    if cvec(j) == 0                 % leave value as zero if c_j is zero
        continue
    end
    
    for k = 1:n
        if cvec(k) == 0             % leave value as zero if c_k is zero
            continue
        end

        if Cmat(j,k) == 0           % if c_{jk} is zero, set W_{jk} to large neg. value
            W(j,k) = log(1/Z);
        else
            W(j,k) = log( Z*Cmat(j,k)/( cvec(j)*cvec(k) ) );      % else use these probs.
        end
    end
end

symmetryCheck = norm(W-W')          % should be 0 if W is symmetric