Saturday, January 12, 2013

PGM2 - Factor Marginalization


#FactorMarginalization Sums given variables out of a factor.
FactorMarginalization <- function(A, V)  {

# Check for empty factor or variable list
if ((length(A$var)==0) || length(V) == 0) B <- A; return;

# Construct the output factor over A.var \ V (the variables in A.var that are not in V)
B.var <- sort(setdiff(A$var, V));
mapB <- match(B.var, A$var);

# Check for empty resultant factor
if (length(B.var)==0) cat('Error: Resultant factor has empty scope');

# Initialize B.card and B.val
B.card <- A$card[mapB];
B.val <- rep(0, prod(B.card));

assignments <- IndexToAssignment(A$card);
assignments$val <- A$val;
assignments$indxB <- AssignmentToIndex(assignments[, mapB], B.card);
tmp1 <- ddply(assignments, .(indxB), function(x) sum(x$val));
B.val <- tmp1$V1[sort(tmp1$indxB)];

B = list(B.var, B.card, B.val);
names(B) = c("var", "card", "val");
return(B);
}

# FACTORS.MARGINALIZATION = FactorMarginalization(FACTORS.INPUT(2), [2]);
#testing 1;
#struct('var', [1], 'card', [2], 'val', [0.11, 0.89]);
A <- data.frame(matrix(c(1,2,0.11,0.89), nrow = 2));
#case1
A.var = c(2, 1);
A.card = c(2, 2);
A.val = c(0.59, 0.41, 0.22, 0.78);
A = list(A.var, A.card, A.val);
names(A) = c("var", "card", "val");
V = c(2);
FactorMarginalization(A,V)

#testing 2;
XX = list(c(3, 2, 1), c(2, 2, 3), c(0.25, 0.35, 0.08, 0.16, 0.05, 0.07, 0, 0, 0.15, 0.21, 0.09, 0.18));
names(XX) = c("var", "card", "val");
V = c(2);
FactorMarginalization(XX,V)

No comments:

Post a Comment