function CPT = mk_CPT_from_noisy_fn(pfail, F, nsc, nsp)
% MK_CPT_FROM_NOISY_FN Make a noisy version of a deterministic function.
% CPT = mk_CPT_from_noisy_fn(pfail, F, nsc, nsp)
% 
% pfail(i,j) is the prob. parent i gets stuck in state j (see the README file)
% nsc is the cardinality of X (node size child)
% nsp(i) is the cardinality of U(i) (node size parent)
% F is a string containing the name of a function F: Z(nsp(1)) x ... x Z(nsp(n)) -> Z(nsc)
% where Z(n) = {1, 2, ..., n}
%
% The results is CPT(U, X), where U has cardinality prod(nsp).

U = prod(nsp);
CPT = zeros(U, nsc);
for ui=1:U
  u = ind2subv(nsp, ui);
  for uni=1:U
    un = ind2subv(nsp, uni);
    x = feval(F, un);
    CPT(ui, x) = CPT(ui, x) + prob_noisy(u, un, pfail);
  end
end

%%%%%%%

function p = prob_noisy(u, un, pfail)

n = length(u);
P = zeros(1,n);
for i=1:n
  pnofail = 1 - sum(pfail(i,:));
  j = un(i);
  if u(i)==un(i)
    P(i) = pnofail + pfail(i,j);
  else
    P(i) = pfail(i,j);
  end
end
p = prod(P);

